Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners

How to Write an Item Listener

Item events are generated by components that implement the ItemSelectable(in the API reference documentation) interface. These are components that maintain state -- generally the on/off state for one or more items. The Swing components that generate item events are [PENDING: check/update list] checkboxes(in the Creating a User Interface trail), checkbox menu items(in the Creating a User Interface trail), and comboboxes(in the Creating a User Interface trail).

Item Event Methods

The ItemListener(in the API reference documentation) interface has just one method, so it has no corresponding adapter class. Here's the method:
void itemStateChanged(ItemEvent)
Called just after a state change in the listened-to component.

Examples of Handling Item Events

Here is some item-event handling code taken from ComponentEventDemo.java:
public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED) {
        label.setVisible(true);
    } else {
        label.setVisible(false);
    }
}

You can find more examples of item listeners in the following source files:

The ItemEvent Class

The itemStateChanged method hod has a single parameter: an ItemEvent(in the API reference documentation) object. The ItemEvent class defines the following handy methods:
Object getItem()
Returns the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item. For an item event generated by a JComboBox, this is an Integer that specifies the index of the selected item [CHECK].
ItemSelectable getItemSelectable()
Returns the component that generated the item event. You can use this instead of the getSource method.
int getStateChange()
Returns the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED.


Previous | Next | Trail Map | Creating a GUI with JFC/Swing | Writing Event Listeners