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