我有一个应用程序,我必须在其中列出与 Arduino 连接的可用端口。我正在使用 RxTx。我当前的代码有一个问题: 在我的 GUI 中,我从该行接收所有端口作为 ArrayList
public ArrayList<String> getPortIdentifiers() {
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
ArrayList<String> ports = new ArrayList<String>();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
ports.add(currPortId.getName());
}
return ports;
}
在我的 Controller 中,我得到这个结果并将结果设置到 View
this.view.setListPorts(listPorts);
在我看来,我得到了 ArrayList 并将数组设置为 ComboBox
new JComboBox(this.listPorts.toArray());
public void setListPorts(ArrayList<String> ports) {
this.listPorts = ports;
}
但是我在该行号上收到错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
最佳答案
这里还有一些代码:
public class CommunicationController implements ActionListener {
public CommunicationController() throws IOException, TooManyListenersException {
// initialize connection here
this.communication = new TestComunication();
ArrayList<String> listPorts = this.communication.getPortIdentifiers();
this.view.setListPorts(listPorts);
}
}
...
public class CommunicationView extends JPanel {
private JComboBox portsList;
private ArrayList<String> listPorts;
public CommunicationView() {
....
.....
this.portsList = new JComboBox(this.listPorts.toArray());
}
public void setListPorts(ArrayList<String> ports) {
this.listPorts = ports;
}
}
......
public class TestComunication {
public ArrayList<String> getPortIdentifiers() {
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
ArrayList<String> ports = new ArrayList<String>();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
ports.add(currPortId.getName());
}
return ports;
}
}
错误
关于java - 将所有端口列为 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570942/