0

我正在将来自 RS32 端口(称重指示器)的值读取到我的 java swing 应用程序中。这些值显示在控制台上。我想要的是在框架中的 jlabel 中显示这些值,而对从端口读取的值几乎没有修改。但我无法为 jlabel 设置值。请帮忙。

我的课是:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
         super();
    }

    void connect (String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() ){
            System.out.println("Error: Port is currently in use");
        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort ) {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.FLOWCONTROL_NONE);

                InputStream in = serialPort.getInputStream();
                (new Thread(new SerialReader(in))).start();

            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }

    public class SerialReader implements Runnable {
        InputStream in;
        BufferedReader reader;

        public SerialReader ( InputStream in ) {
            this.in = in;
            this.reader = new BufferedReader(new InputStreamReader(in));
        }

        public void run () {
            String line = null;

            try{
               while ((line = reader.readLine()) != null) {
                   System.out.println("Read line with " + line.length() + " characters: \"" + line + "\"");
                   lblRead.setText(line);
               }
            }
            catch ( IOException e ) {
                e.printStackTrace();
            }            
        }

    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
                try {
                    (new NewJFrame()).connect("/dev/ttyUSB0");
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel lblRead;
    // End of variables declaration
}
4

1 回答 1

1

而不是一个new Thread(),扩展SwingWorker。您可以读取实现中的串行端口doInBackground()publish()中间结果,并在process(). Counter是一个简单的例子。

于 2013-10-04T11:34:12.507 回答