Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过rxtx库和SerialPortEvent接收JAVA中的数据,并在jTextArea中显示字符串文本_Java_User Interface_Arduino_Serial Port_Rxtx - Fatal编程技术网

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

通过rxtx库和SerialPortEvent接收JAVA中的数据,并在jTextArea中显示字符串文本,java,user-interface,arduino,serial-port,rxtx,Java,User Interface,Arduino,Serial Port,Rxtx,这就是问题所在,我有一个Arduino uno r3,它通过串行端口发送数据,我有一个java gui代码来接收字节[]数组中的数据,将其转换并存储在字符串st中,然后在jTextArea中显示。 问题是jtextArea没有显示任何内容,可能考虑到字符串st值为null,但是如果我使用著名的System.out.print(st),结果会正确地显示在控制台中。 我不知道出了什么问题,我在下面发布了一段负责从串口获取数据的代码,synchronized serialEvent方法,非常感谢您的帮

这就是问题所在,我有一个Arduino uno r3,它通过串行端口发送数据,我有一个java gui代码来接收字节[]数组中的数据,将其转换并存储在字符串st中,然后在jTextArea中显示。 问题是jtextArea没有显示任何内容,可能考虑到字符串st值为null,但是如果我使用著名的System.out.print(st),结果会正确地显示在控制台中。 我不知道出了什么问题,我在下面发布了一段负责从串口获取数据的代码,synchronized serialEvent方法,非常感谢您的帮助,请帮助我:) 请注意,jTextArea1在同一类中声明为private,字符串st在同一类中声明为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                   

    }
import java.io.*;
导入java.io.InputStream;
导入java.io.IOException;
导入java.io.OutputStream;
导入javax.swing.JTextArea;
导入javax.swing.JOptionPane;
导入java.io.OutputStream;
输入gnu.io.CommPortIdentifier;
导入gnu.io.SerialPort;
导入gnu.io.SerialPortEvent;
导入gnu.io.SerialPortEventListener;
导入java.nio.charset.charset;
导入java.util.Enumeration;
导入java.util.logging.Level;
导入java.util.logging.Logger;
公共类读取扩展了javax.swing.JFrame实现了SerialPortEventListener{
串行端口串行端口;
公共静态字符串st;
公共字符[]c;
/**
*创造新的阅读形式
*/
专用静态最终字符串端口名称[]={
“/dev/tty.usbmodem411”,//Mac OS X
“/dev/ttyUSB0”,//Linux
“COM3”//Windows
};
私有输入流输入;
私有输出流输出;
专用静态最终整数超时=2000;
专用静态最终整数数据率=9600;
公众阅读(){
初始化组件();
初始化();
close();
}
公共无效初始化(){
CommPortIdentifier portId=null;
枚举portEnum=CommPortIdentifier.getPortIdentifiers();
//遍历,查找端口
while(portEnum.hasMoreElements()){
CommPortIdentifier currPortId=(CommPortIdentifier)portEnum.nextElement();
for(字符串端口名称:端口名称){
if(currPortId.getName().equals(portName)){
portId=currPortId;
打破
}
}
}
if(portId==null){
jTextArea1.setText(“扫描仪未连接!”);
}
试一试{
serialPort=(serialPort)portId.open(this.getClass().getName(),
超时);
//设置端口参数
serialPort.setSerialPortParams(数据速率,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
串行端口。奇偶校验(无);
input=serialPort.getInputStream();
output=serialPort.getOutputStream();
//添加事件侦听器
serialPort.addEventListener(此);
serialPort.notifyOnDataAvailable(true);
}捕获(例外e){
}
}     
公共同步的void close(){
如果(serialPort!=null){
serialPort.removeEventListener();
serialPort.close();
}
}    
公共同步的void serialEvent(SerialPortEvent oEvent){
如果(oEvent.getEventType()==SerialPortEvent.DATA_可用){
试试{
int available=input.available();
字节[]块=新字节[可用];
读取(块,0,可用);
st=新字符串(块);
jTextArea1.追加(st);
系统输出打印(st);
试一试{
睡眠(5000);
}捕获(中断异常例外){
Thread.currentThread().interrupt();
}                                                                                                                                                                                           
//显示的结果取决于代码页
}
捕获(IOE异常){
System.out.println(“发生IO错误:+e.toString());
}          
}
/忽略所有其他事件类型,但您应该考虑其他事件类型。
}        
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/    
//                                                                                              
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jScrollPane1=newjavax.swing.JScrollPane();
jTextArea1=newjavax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.设置列(20);
jTextArea1.设置行(5);