Listening for Changes to the Selected Item in a JComboBox Component
Item events are generated whenever the selected item changes. These
events are generated even while the user is moving through items in
the displayed popup menu. If the combobox is editable, this event
does not indicate whether the new item is taken from the predefined
list or not. If this information is necessary, see
Listening for Action Events from a JComboBox Component.
// Create an editable combobox
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);
// Create and register listener
MyItemListener actionListener = new MyItemListener();
cb.addItemListener(actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get the affected item
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
Post a comment