在Swing中使用数组列表填充组合框

时间:2017-01-13 12:39:40

标签: java swing arraylist combobox jcombobox

我创建了一个带有组合框的GUI,我希望用ArrayList填充它。我试过我的编码,但它不起作用。

private void jcbSourceActionPerformed(java.awt.event.ActionEvent evt) {                                          
      ArrayList al=new ArrayList();
        al.add("A");
        al.add("B");
        al.add("C");
        al.add("D");
        al.add("E");

        jcbSource.setModel(new DefaultComboBoxModel(al.toArray()));
        jcbSource.addItem(al.toString());
    }

1 个答案:

答案 0 :(得分:1)

尝试为通用设置String类型,即使用JComboBox<String> ArrayList<String>DefaultComboBoxModel<String>,如下例所示

public class Test extends JFrame {
    public Test() {
        getContentPane().setLayout(new FlowLayout());
        final JComboBox<String> jcbSource = new JComboBox<String>();
        jcbSource.setSize(new Dimension(30, 20));
        add(jcbSource);

        JButton setupButton = new JButton("Setup model");
        setupButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ArrayList<String> al = new ArrayList<String>();
                al.add("A");
                al.add("B");
                al.add("C");
                al.add("D");
                al.add("E");

                String[] items = new String[al.size()];
                al.toArray(items);

                jcbSource.setModel(new DefaultComboBoxModel<String>(items));
            }
        });
        add(setupButton);

        pack();
    }

    public static void main(String[] args){
        new Test().setVisible(true);
    }
}
相关问题