java - 将所有端口列为 JComboBox

标签 java swing arduino

我有一个应用程序,我必须在其中列出与 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;
    }
}

错误 enter image description here

关于java - 将所有端口列为 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28570942/

相关文章:

java - 如何创建自定义 JComponent(如 JButton),忽略当前的外观

c++ - 数组 + union + 包含位字段 C++ 的结构

c - 如何在 Arduino Due 中创建精确的计时器

java - 如何使用 Spring Boot 检测并禁止 IP 地址发出过多请求?

java - 浏览器请求正常,java请求301

Java Jar 控制台应用程序打开 Mac 系统菜单栏

java - 在 JTable 中显示实体属性值数据?

java - 使用处理连接arduino串口的问题

java - 试图解压缩 BC1 纹理压缩的扰乱 block

java - selenium.click() 不起作用 : Argument 1 of EventTarget. dispatchEvent 没有实现接口(interface)事件