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

Populate combo box with array list in Swing

我创建了一个带有组合框的 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());
    }

尝试为泛型设置 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);
    }
}