Reputation: 3
I create an GUI with an combo box which I want to populate with ArrayList
. I tried with my coding but it doesn't work.
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());
}
Upvotes: 0
Views: 2027
Reputation: 5371
Try to set String
type for generics, i.e. use JComboBox<String>
ArrayList<String>
and DefaultComboBoxModel<String>
like in example below
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);
}
}
Upvotes: 1