通过 rxtx 库和 SerialPortEvent 在 JAVA 中接收数据,在 jTextArea 中显示字符串文本

receive data in JAVA via rxtx library and SerialPortEvent displaying string text in jTextArea

现在是问题所在,我有一个通过串行端口发送数据的 Arduino uno r3,我有一个 java gui 代码来接收字节 [] 数组中的数据,将其转换并存储在字符串中st 并将其显示在 jTextArea 中。 问题是 jtextArea 不显示任何东西,可能考虑到字符串 st 值为 null,但如果我使用著名的 System.out.print(st),结果会在控制台中正确显示。 我不知道怎么了,我在下面发布了一段负责从串口获取数据的代码,同步的 serialEvent 方法,任何帮助将不胜感激,请帮助我:) 请注意,jTextArea1 在同一个 class 中被声明为私有,而 String st 在同一个 class 中被声明为 public 非常感谢

public synchronized void serialEvent(SerialPortEvent oEvent) { 
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {           
        try {                 
                int available = input.available();
            byte[] chunk = new byte[available];
            input.read(chunk, 0, available);
            st = new String(chunk);
            jTextArea1.append(st);                                
        }catch (IOException e) {System.out.println("IO Error Occurred: " + e.toString());}

这是完整的 JAVA 代码,从 NetBeans IDE 复制粘贴,此代码运行并毫无问题地输出到控制台,即使我创建了一个 JButton 并关联打印字符串到 JButton 下的 jTextArea 单击它可以工作,但问题是自动将字符串附加到代码本身中的 jTextArea :

    import java.io.*;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
import javax.swing.JOptionPane;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
public class reading extends javax.swing.JFrame implements SerialPortEventListener{
    SerialPort serialPort;
    public static String st;
    public  char[] c;
    /**
     * Creates new form reading
     */
    private static final String PORT_NAMES[] = {
            "/dev/tty.usbmodem411", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
            };
    private InputStream input;
    private OutputStream output;   
    private static final int TIME_OUT = 2000;    
    private static final int DATA_RATE = 9600;
    public reading() {
        initComponents();
        initialize();
        close();    
    }
    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        // iterate through, looking for the port
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
                              jTextArea1.setText("scanner is not connected ! ");
        }
        try {
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);
            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {            
        }
    }     
    public synchronized void close() { 
       if (serialPort != null) {
           serialPort.removeEventListener();
           serialPort.close();
        }
       }    
    public synchronized void serialEvent(SerialPortEvent oEvent) {       
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {           
            try {                 
                    int available = input.available();
                byte[] chunk = new byte[available];
                input.read(chunk, 0, available);
                st = new String(chunk);
                jTextArea1.append(st);
                System.out.print(st);
                try{
                Thread.sleep(5000);                 
} catch(InterruptedException ex) {
    Thread.currentThread().interrupt();
}                                                                                                                                                                                           
                // Displayed results are codepage dependent                                                                                                                                                                                                                                       
            }
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());

}          
        }
       // Ignore all the other eventTypes, but you should consider the other ones.
    }        
    /**
     * 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.
     */    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                                                                                             
    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(211, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(179, Short.MAX_VALUE))
        );

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

    /**
     * @param args the command line arguments
     */
    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(reading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(reading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(reading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(reading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
reading main = new reading();
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new reading().setVisible(true);
                main.initialize();
            }
        });
    }      
    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration                   

    }

好的,我明白了!我必须首先在 JFrame 中创建一个 jPanel 并将所有组件添加到其中,而不是直接在 JFrame 中添加组件!现在它就像一个魅力!非常感谢您的关心。