简体   繁体   English

如何使用Array或ArrayList中的值加载JComboBox?

[英]How do I load a JComboBox with values from an Array or ArrayList?

I need to put the following array into a JComboBox and then store the selected value when the "Submit" button is clicked. 我需要将以下数组放入JComboBox,然后在单击“提交”按钮时存储选择的值。

    listOfDepartments = new String[5];
    listOfDepartments[0] = "Mens Clothing";
    listOfDepartments[1] = "Womens Clothing";
    listOfDepartments[2] = "Childrens Clothing";
    listOfDepartments[3] = "Electronics";
    listOfDepartments[4] = "Toys";

    //Department: ComboBox that loads from array

    // Store values
    JButton buttonSubmit = new JButton();
    buttonSubmit.setText("Submit");
    container.add(buttonSubmit);

     buttonSubmit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
        //store value from combobox in a variable
        }
    });

First, create a model... 首先,建立模型...

DefaultComboBoxModel model = new DefaultComboBoxModel(listOfDepartments);
comboBox.setModel(model);

Second, get the selected value when the actionPerformed event is raised... 其次,在引发actionPerformed事件时获取选定的值...

String value = (String)comboBox.getSelectedItem();

Take a look at How to Use Combo Boxes for more details. 查看更多如何使用组合框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM