ItemListener

ItemListeners are used to respond to item events. These are generated whenever an item's state changes. Typically, this occurs when an item is selected or deselected from a check box or a radio button. If, for example, a particular radio button is currently selected and another radio button is clicked, the item event is fired twice: once when the current radio button is deselected, and a second time when the new radio button is selected. The ItemListener interface consists of a single method, itemStateChanged. Specifically, this method has the signature

void itemStateChanged(ItemEvent e);

where e is an object of type ItemEvent. The java.awt.event.ItemEvent class contains a number of methods, including getSource. As with an action event, getSource returns the object that generated the event.

As an example, suppose we have registered an item listener for a check box, tradeButton. This could represent the Trade Customer check box in Figure 8.1. The itemStateChanged method is shown next.
itemStateChanged

public void itemStateChanged (ItemEvent e)
{
if (e.getSource() instanceof JCheckBox)
{
JCheckBox buttonLabel = (JCheckBox)
e.getItemSelectable();
if (buttonLabel == tradeButton)
{
if (e.getStateChange() == e.SELECTED) {
System.out.println(''Customer is trade");
}
else
{
System.out.println("Customer is not trade");
}
}
}
}

The statement (line 2)

if (e.getSource() instanceof JCheckBox) {

determines whether the event source is a check box. In that case, in lines 3–4, we use the java.awt.event.ItemEvent.getItemSelectable method to obtain the originator of the item event. This is then cast to a JCheckBox, buttonLabel. We can then use the ItemEvent.getState-Change method to determine whether tradeButton has been checked.

No comments:

Post a Comment