Java GUI使用ArrayList填充组合框值

时间:2014-05-29 14:12:18

标签: java user-interface netbeans arraylist combobox

我正在尝试使用ArrayList的值填充ComboBox,但我不知道如何。我希望数据从ArrayList COM = new ArrayList();出来。我已经拥有的东西:

private void initComponents() {
    selectedComPort = new javax.swing.JComboBox();

    selectedComPort.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM 1", "COM 2" }));
    selectedComPort.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            selectedComPortActionPerformed(evt);
        }
    });
}

private void selectedComPortActionPerformed(java.awt.event.ActionEvent evt) {

}

public static void main(String args[]) {
    // Search all available COM ports and put them into a ArrayList
    ArrayList<String> COM = new ArrayList<String>();
    Enumeration portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
            System.out.println("No COM ports found");
            } else {
            COM.add(portId.getName());
        }
    }
    System.out.println(COM);
}

private javax.swing.JComboBox selectedComPort;

1 个答案:

答案 0 :(得分:1)

尝试,

private void initComponents() {
 List<String> COM = new ArrayList<String>();
 Enumeration portList = CommPortIdentifier.getPortIdentifiers();
 while (portList.hasMoreElements()) {
    CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
        System.out.println("No COM ports found");
        } else {
        COM.add(portId.getName());
    }
}

 selectedComPort = new JComboBox(COM.toArray(new String[COM.size()]));
 ....
}