所以,我正在制作一个通过发送命令与传感器通信的程序。但是,当我尝试单击 GUI 中的按钮时,会出现两个错误:空指针异常和 portinuse 异常,这会阻止按钮工作。我该如何解决?
简单阅读类:
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.comm.*;
import javax.swing.*;
public class SimpleRead {
static Enumeration portList;
static CommPortIdentifier portId;
static PrintStream os;
static BufferedReader is;
static java.util.Timer t = new java.util.Timer();
static TimersTask tt = new TimersTask();
public static void main(String[] args) {
GUI GUI = new GUI();
JFrame window = new JFrame("DI-100");
window.setSize(700, 300);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(GUI);
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
String wantedPortName;
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
ArrayList<String> serialports = new ArrayList<String>();
serialports.add(portId.getName());
String[] ports = new String[serialports.size()];
ports = serialports.toArray(ports);
GUI.jComboBox2 = new JComboBox(ports);
GUI.jComboBox2.addActionListener(GUI.jComboBox2);
wantedPortName = (String) GUI.jComboBox2.getSelectedItem();
while (portList.hasMoreElements()) {
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
portId.getName().equals(wantedPortName)) {
CommPortIdentifier pid = portId;
SerialPort port = null;
try {
port = (SerialPort) portId.open("OpenPort", 1000);
} catch(PortInUseException e) {
System.err.println("Port already in use: " + e);
}
try {
port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
}
catch (UnsupportedCommOperationException e) {
System.out.println("you suck");
}
try {
os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
}
catch (IOException e) {
System.err.println("Can't open input stream: write-only");
}
try {
is = new BufferedReader(new InputStreamReader(port.getInputStream()));
} catch (IOException e) {
System.err.println("Can't open input stream: write-only");
}
try{
os = new PrintStream(port.getOutputStream(), true);
} catch (IOException e){
}
}
else {
}
}
}
}
}
TimersTask 类:
import java.io.IOException;
import java.util.*;
public class TimersTask extends TimerTask{
@Override
public void run() {
SimpleRead.os.print("W");
try {
String returnvalue = SimpleRead.is.readLine();
System.out.println(returnvalue);
GUI.jTextField1.setText(returnvalue);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
//is.readLine(); // Second read will remove the extra line feed that AT generates as
} catch (IOException e){
}
}
}