使用 Swing 和 RXTX 进行 Java RS232 通信

标签 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                   
}

最佳答案

您的输出可能与 EventDispatcherTread 不同步。尝试以下操作:

    SwingUtilities.invokeLater(new Runnable() {

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

关于使用 Swing 和 RXTX 进行 Java RS232 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38635568/

相关文章:

Java增量运算符查询(++i和i++)

java - Hibernate 多对多映射和 cascade=delete

java - 意外的类型错误

java - 如何实现这个功能呢?

java - 将 javaFX (.jar) 文件导入 Netbeans Maven 项目

java - 获取在接口(interface)方法中分配的返回值作为方法?

java - GUI 卡布局 - 操作监听器不工作

java - 将图表插入内部 jframe

c++ - NetBeans C++ 在错误的位置寻找 make 实用程序

java - 要在 jlist 中显示的联网计算机名称