Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Meta en 6 Marzo 2015, 21:33 pm



Título: Leer puerto serie y mostrar texto en cuadro de texto
Publicado por: Meta en 6 Marzo 2015, 21:33 pm
Hola:

Uso Windows 7 de 64 bits con Java de 32 para que me funcione el famoso RXTX.

(http://www.subeimagenes.com/img/fsdafasdfsad-1244703.png)

He hecho una aplicación sencilla que se puede encender un Led y apagarlo con NetBeans 8 como puedes ver en la imagen de arriba.

1) Cuando el Form o formulario o ventana está abierta o ejecuto Java, me aparece arriba a la izquierda. ¿Cómo se pone en el centro cuando ejecutes a apliación?

2) Ahora quiero hacer un cuadro de texto para que muestre los textos que te entran en el puerto serie.

¿Alguna idea?

Su código para encender y apagar un Led es este.
Código
  1. import gnu.io.CommPortIdentifier;
  2. import gnu.io.SerialPort;
  3. import java.io.OutputStream;
  4. import java.util.Enumeration;
  5. import javax.swing.JOptionPane;
  6.  
  7. /*
  8.  * To change this license header, choose License Headers in Project Properties.
  9.  * To change this template file, choose Tools | Templates
  10.  * and open the template in the editor.
  11.  */
  12.  
  13. /**
  14.  *
  15.  * @author Meta
  16.  */
  17. public class JAVADUINO_Frame extends javax.swing.JFrame {
  18.  
  19.    /**
  20.      * Creates new form JAVADUINO_Frame
  21.      */
  22.  
  23.    private static final String L8on = "Led_8_ON";
  24.    private static final String L8off = "Led_8_OFF";
  25.  
  26.    // Variables de conexión.
  27.    private OutputStream output = null;
  28.    SerialPort serialPort;
  29.    private final String PUERTO = "COM4";
  30.  
  31.    private static final int TIMEOUT = 2000; // 2 segundos.
  32.  
  33.    private static final int DATA_RATE = 115200; // Baudios.
  34.  
  35.    public JAVADUINO_Frame() {
  36.        initComponents();
  37.        inicializarConexion();
  38.    }
  39.  
  40.    public void inicializarConexion(){
  41.        CommPortIdentifier puertoID = null;
  42.        Enumeration puertoEnum = CommPortIdentifier.getPortIdentifiers();
  43.  
  44.        while (puertoEnum.hasMoreElements()){
  45.            CommPortIdentifier actualPuertoID = (CommPortIdentifier) puertoEnum.nextElement();
  46.            if (PUERTO.equals(actualPuertoID.getName())){
  47.                puertoID = actualPuertoID;
  48.                break;
  49.            }
  50.        }
  51.  
  52.        if (puertoID == null){
  53.            mostrarError("No se puede conectar al puerto");
  54.            System.exit(ERROR);
  55.        }
  56.  
  57.        try{
  58.            serialPort = (SerialPort) puertoID.open(this.getClass().getName(), TIMEOUT);
  59.            // Parámatros puerto serie.
  60.  
  61.            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
  62.  
  63.            output = serialPort.getOutputStream();
  64.        } catch (Exception e){
  65.            mostrarError(e.getMessage());
  66.            System.exit(ERROR);
  67.        }
  68.    }
  69.  
  70.    private void enviarDatos(String datos){
  71.        try{
  72.            output.write(datos.getBytes());
  73.        } catch (Exception e){
  74.            mostrarError("ERROR");
  75.            System.exit(ERROR);
  76.        }
  77.    }
  78.  
  79.    public void mostrarError(String mensaje){
  80.        JOptionPane.showMessageDialog(this, mensaje, "ERROR", JOptionPane.ERROR_MESSAGE);    
  81.    }
  82.    /**
  83.      * This method is called from within the constructor to initialize the form.
  84.      * WARNING: Do NOT modify this code. The content of this method is always
  85.      * regenerated by the Form Editor.
  86.      */
  87.    @SuppressWarnings("unchecked")
  88.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  89.    private void initComponents() {
  90.  
  91.        jButton1 = new javax.swing.JButton();
  92.        jButton2 = new javax.swing.JButton();
  93.        jLabel1 = new javax.swing.JLabel();
  94.        jScrollPane1 = new javax.swing.JScrollPane();
  95.        jTextArea1 = new javax.swing.JTextArea();
  96.  
  97.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  98.        setTitle("JAVA y más Java");
  99.  
  100.        jButton1.setText("ON");
  101.        jButton1.addActionListener(new java.awt.event.ActionListener() {
  102.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  103.                jButton1ActionPerformed(evt);
  104.            }
  105.        });
  106.  
  107.        jButton2.setText("OFF");
  108.        jButton2.addActionListener(new java.awt.event.ActionListener() {
  109.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  110.                jButton2ActionPerformed(evt);
  111.            }
  112.        });
  113.  
  114.        jLabel1.setText("Mensaje desde el puerto serie:");
  115.  
  116.        jTextArea1.setColumns(20);
  117.        jTextArea1.setRows(5);
  118.        jScrollPane1.setViewportView(jTextArea1);
  119.  
  120.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  121.        getContentPane().setLayout(layout);
  122.        layout.setHorizontalGroup(
  123.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  124.            .addGroup(layout.createSequentialGroup()
  125.                .addContainerGap()
  126.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  127.                    .addGroup(layout.createSequentialGroup()
  128.                        .addComponent(jButton1)
  129.                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  130.                        .addComponent(jButton2))
  131.                    .addGroup(layout.createSequentialGroup()
  132.                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  133.                        .addGap(0, 0, Short.MAX_VALUE)))
  134.                .addContainerGap())
  135.            .addGroup(layout.createSequentialGroup()
  136.                .addComponent(jLabel1)
  137.                .addGap(0, 0, Short.MAX_VALUE))
  138.        );
  139.        layout.setVerticalGroup(
  140.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  141.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  142.                .addGap(26, 26, 26)
  143.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  144.                    .addComponent(jButton1)
  145.                    .addComponent(jButton2))
  146.                .addGap(31, 31, 31)
  147.                .addComponent(jLabel1)
  148.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  149.                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
  150.                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
  151.        );
  152.  
  153.        pack();
  154.    }// </editor-fold>                        
  155.  
  156.    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  157.        // TODO add your handling code here:
  158.        enviarDatos(L8on);
  159.    }                                        
  160.  
  161.    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
  162.        // TODO add your handling code here:
  163.        enviarDatos(L8off);
  164.    }                                        
  165.  
  166.    /**
  167.      * @param args the command line arguments
  168.      */
  169.    public static void main(String args[]) {
  170.        /* Set the Nimbus look and feel */
  171.        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  172.        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  173.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  174.          */
  175.        try {
  176.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  177.                if ("Nimbus".equals(info.getName())) {
  178.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  179.                    break;
  180.                }
  181.            }
  182.        } catch (ClassNotFoundException ex) {
  183.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  184.        } catch (InstantiationException ex) {
  185.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  186.        } catch (IllegalAccessException ex) {
  187.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  188.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  189.            java.util.logging.Logger.getLogger(JAVADUINO_Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  190.        }
  191.        //</editor-fold>
  192.  
  193.        /* Create and display the form */
  194.        java.awt.EventQueue.invokeLater(new Runnable() {
  195.            public void run() {
  196.                new JAVADUINO_Frame().setVisible(true);
  197.            }
  198.        });
  199.    }
  200.  
  201.    // Variables declaration - do not modify                    
  202.    private javax.swing.JButton jButton1;
  203.    private javax.swing.JButton jButton2;
  204.    private javax.swing.JLabel jLabel1;
  205.    private javax.swing.JScrollPane jScrollPane1;
  206.    private javax.swing.JTextArea jTextArea1;
  207.    // End of variables declaration                  
  208. }
  209.  

Saludos.