使用Swing和RXTX进行Java RS232通信

时间:2016-07-28 11:52:36

标签: java swing netbeans serial-port rxtx

我尝试使用串口在我的PC(使用Netbeans和RXTX的Windows 7)之间进行通信。我有一个串行事件的问题(public void serialEvent(SerialPortEvent arg0))。此事件应该重新获取数据并将其写入标签(jLabel1.setText(" sfazds"))。不幸的是,这个事件不会改变标签文本,我现在不知道为什么。以下是我的代码:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class RS extends javax.swing.JFrame implements SerialPortEventListener{

    static OutputStream out;
    static InputStream in;

    public RS() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("jLabel1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(203, 203, 203)
                        .addComponent(jLabel1)))
                .addContainerGap(217, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jButton1)
                .addGap(34, 34, 34)
                .addComponent(jLabel1)
                .addContainerGap(222, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        byte[] b = new byte[2];
        b[0] = 'a';
        b[1] = 'b';
        try{
            out.write(b);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }                                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        try{
            (new RS()).connect("COM3");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }                                 

    void connect(String portName) throws Exception{
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()){
            JOptionPane.showMessageDialog(null, "Błąd: Port jest obecnie w użyciu");
        }
        else{
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
            if (commPort instanceof SerialPort){
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            }     
            else{
                JOptionPane.showMessageDialog(null, "Tylko port szeregowy może być podłączony!");
            }
        }
    }
    @Override
    public void serialEvent(SerialPortEvent arg0) {
            int data;
            byte[] buffer = new byte[1024];
            try{
                int len = 0;
                while ( ( data = in.read()) > -1 ){
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print(new String(buffer,0,len));
                jLabel1.setText("sfazds");
                JOptionPane.showMessageDialog(null, new String(buffer,0,len));
            }
            catch ( IOException e ){
                System.exit(-1);
            }             
        }

    public static class SerialWriter implements Runnable{
        OutputStream out;

        public SerialWriter(OutputStream out){
            this.out = out;
        }

        @Override
        public void run(){
            try{
                int c = 0;
                while ((c = System.in.read()) > -1){
                    this.out.write(c);
                }
            }
            catch(IOException e){
                System.exit(-1);
            }
        }
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RS().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:1)

您的输出可能与EventDispatcherTread未同步。请尝试以下方法:

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            jLabel1.setText("sfazds");
        }
    });