How to Write an Item Listener

 <  Day Day Up  >  

Item events are fired by components that implement the ItemSelectable interface. [15] Generally, ItemSelectable components maintain on/off state for one or more items. The Swing components that fire item events include check boxes, check box menu items, and combo boxes.

[15] ItemSelectable API documentation: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/ItemSelectable.html.

Here's some item event-handling code taken from ComponentEventDemo.java : [16]

[16] This source code is on the CD at: JavaTutorial/uiswing/events/example-1dot4/Component-EventDemo.java .

  //Where initialization occurs:  checkbox.addItemListener(this); ... public void itemStateChanged(ItemEvent e) {     if (e.getStateChange() == ItemEvent.SELECTED) {         label.setVisible(true);         ...     } else {         label.setVisible(false);     } } 

The Item Listener API

Table 16 lists the methods in the ItemListener interface and Table 17 describes the methods in the ItemEvent class. Because ItemListener has only one method, it has no corresponding adapter class. Also refer to the API documentation for the ItemListener interface online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ItemListener.html. The API documentation for ItemEvent is online at: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/event/ItemEvent.html.

Table 16. The ItemListener Interface

Method

Purpose

itemStateChanged(ItemEvent)

Called just after a state change in the listened-to component.

Table 17. The ItemEvent Class

Method

Purpose

Object getItem()

Return the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item.

ItemSelectable getItemSelectable()

Return the component that fired the item event. You can use this instead of the getSource method.

int getStateChange()

Return the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED .

Examples That Use Item Listeners

The following table lists some examples that use item listeners.

Example

Where Described

Notes

ComponentEventDemo

This section and How to Write a Component Listener (page 654)

Listens for item events on a check box, which determines whether a label is visible.

CheckBoxDemo

How to Use Check Boxes (page 163)

Four check boxes share one item listener, which uses getItemSelected to determine which check box fired the event.

MenuDemo

How to Use Menus (page 277)

Listens for item events on a check box menu item.

ScrollDemo

How to Use Scroll Panes (page 325)

Listens for item events on a toggle button.

 <  Day Day Up  >  


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net