for (int i = 1; i <= 100; ++i) {
ageList.add(i);
}
DefaultComboBoxModel<Integer> modelAge = new DefaultComboBoxModel<Integer>();
for (Integer i : ageList) {
modelAge.addElement(i);
}
JComboBox<Integer> ageEntries = new JComboBox<Integer>();
ageEntries.setModel(modelAge);
ageEntries.addItemListener(new ageListener());
class ageListener implements ItemListener{
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
System.out.println("Selected:" + ItemEvent.SELECTED);
}
}
}
Problem: When I choose an age, it prints out 1, regardless of the age I’ve choosed. For example, if I choose the number 7, it prints out 1. If I choose 56, it prints out 1. Any ideas? I’m stumped.
Use this to retrieve the selected item ..
EDIT: should be
((JComboBox<Integer>)event.getSource()).getSelectedItem();as you are using generics. And “Yes” this will come inside your event method.EDIT 2: you are getting the warning because we cannot determine whether JComboBox should have a Generic parameter. Compiler raises this warning because it thinks its unsafe to do such casting.