I have a Person [ ] with three Persons (p1,p2,p3). Person class has two attributes name and email.
I want to add all names of Person[] in one JComboBox and all emails in another JComboBox.
I used the following code.
Person p1 = new Person("Smith", "smith@mail.com");
Person p2 = new Person("Tom", "tom@gmail.com");
Person p3 = new Person("John","john@mail.com");
Person[] per_arr = new Person[] { p1, p2, p3};
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JComboBox<String> combo1 = new JComboBox<String>();
JComboBox<String> combo2 = new JComboBox<String>();
for (Person p : per_arr) {
combo1.addItem(p.getName());
combo2.addItem(p.getEmail());
}
panel.add(combo1);
panel.add(combo2);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
But I don't want to used like this. I'd like to use the two combo boxes with the same model. I tried with DefaultComboBoxModel and Override getElementAt() method like the following.
public class MyModel extends DefaultComboBoxModel<Object> {
public MyModel(Object[] items) {
super(items);
}
@Override
public Object getElementAt(int index) {
if (super.getElementAt(index) instanceof Person) {
return (Person)super.getElementAt(index);
} else {
return null;
}
}
}
The above ComboBoxModel give me only the Person objects.
The Question is how can I add all names of Person[] in one JComboBox and all emails in another JComboBox using same ComboBoxModel .
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…