从 JFrame Class 调用串行端口 Class

Calling Serial Port Class from a JFrame Class

我正在通过串行端口与 Arduino 一起试验 Java 的 JFrame,但我 运行 遇到了问题,我不确定如何继续我的代码。

我正在尝试使用构造函数从另一个 class 中的 JFrame 代码调用一个 class 的串行端口部分。基本上,我正在尝试将我的 Java 程序与 Arduino Uno 连接起来。

我的问题是,当我尝试 运行 来自 GUI class 的代码时,在 SerialOut.write("test".getBytes());,错误提示 "Exception in thread "main" java.lang.NullPointerException".

有人可以看看构造函数并告诉我是否有错误吗?谢谢!

Class 用于设置串行端口此代码本身有效 [我使用 Uno 和 LED 测试它是否亮起。 (确实如此)]

package javaapplication1;

import javaapplication1.RCDA_JFrame;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;
import java.io.IOException;

public class SerialTest implements SerialPortEventListener {
        //constructor
        public SerialTest(){
            this.initialize();
            this.close();
            this.serialEvent(null);
        }        
    SerialPort serialPort;
        /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = { 
            "COM8",}; // Windows 
    private BufferedReader input;
    private static OutputStream SerialOut;/** The output stream to the port */
    private static final int TIME_OUT = 2000;/** Milliseconds to block while waiting for port open */
    private static final int DATA_RATE = 9600;/** Default bits per second for COM port. */

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            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);
            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            SerialOut = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }
    //Handle an event on the serial port. Read the data and print it.
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }
    public static void main(String[] args) throws Exception {

        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
        //testing
                try {
                System.out.println("This is a test");
                System.out.println("test".getBytes());
                SerialOut.write("test".getBytes()); //SEND STRING THROUGH SERIAL PORT
        } catch (IOException e1) {
                        e1.printStackTrace();
        } //end of testing
    }
}

JFrame class - 我试图调用上面的 class 的地方:

package javaapplication1;

import javaapplication1.SerialTest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;
import java.io.IOException;

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

    @Override
    public void serialEvent(SerialPortEvent ev) {
    SerialTest ST1 = new SerialTest();
    }
    private static OutputStream SerialOut;
    SerialPort serialPort;
        /** The port we're normally going to use. */
//    private static final String PORT_NAMES[] = { 
//          "COM8"}; // Windows 
//    private BufferedReader input;
//    private static final int TIME_OUT = 2000;/** Milliseconds to block while waiting for port open */
//    private static final int DATA_RATE = 9600;/** Default bits per second for COM port. */
//    
    public NewJFrame() {
        initComponents();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

public static void main(String args[]) {
        //constructor from SerialTest
        SerialTest ST1 = new SerialTest();

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

        try {
            System.out.println("This is a test");
            System.out.println("test".getBytes());
              SerialOut.write("test".getBytes()); //SEND STRING THROUGH SERIAL PORT
            } catch (IOException e1) {
        e1.printStackTrace();
        }
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}
private static OutputStream SerialOut;/** The output stream to the port */

这是在 SerialTest. 注意它不应该是静态的。它在您调用 initialize() 时初始化,前提是找到了一个端口,并且由于 initialize() 不会抛出异常或 return 任何状态,因此无法知道它是否成功。解决这个问题。

private static OutputStream SerialOut;

NewJFrame 中。它与前一个数据项不同。它根本没有被初始化,所以它是空的,所以你得到一个 NullPointerException。删除它,并使用 SerialTest.

中的那个

在检查可用端口列表后,您有一个错误检查以查看端口是否为空。确保它确实获得了可用的端口,并且你确实有一个值被分配给它。

if (portId == null) {
     System.out.println("Could not find COM port.");
     return;
}

要确认尝试打印出 portName 以查看它实际上变成了哪个端口 portId.getName() 并检查以确保它不为空。如果是,那就是你的问题。