ItemListeners

When the user changes the selected item in a Choice, the Choice fires two ItemListener events, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering an ItemListener object with your Choice.

You do not always need to do this. It is not uncommon to only check the value of a Choice when some other event occurs like a Button press.

For example, the following applet builds a Choice menu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class MultiBeep extends Applet {
  
  public void init() {

    Choice ch;
    ch = new Choice();
    ch.addItem("1");
    ch.addItem("2");
    ch.addItem("3");
    ch.addItem("4");
    ch.addItem("5");
    this.add(ch);
    ch.addItemListener(new BeepItem());

  }    

}


class BeepItem implements ItemListener {

  public void itemStateChanged(ItemEvent ie) {

    if (ie.getStateChange() == ItemEvent.SELECTED) {
      String name = (String) ie.getItem();
      Toolkit tk = Toolkit.getDefaultToolkit();
      try {
        int n = Integer.parseInt(name);
        for (int i = 0; i < n; i++) tk.beep();
      }
      catch (Exception e) {
        tk.beep();
      }
    }

  }

}
The BeepItem class implements the ItemListener interface. It filters out events caused by items being deselected with ItemEvent.getStateChange() and only beeps if an item was selected. The available convenience constants you can check are:

ItemEvent.DESELECTED 
ItemEvent.ITEM_FIRST 
ItemEvent.ITEM_LAST 
ItemEvent.ITEM_STATE_CHANGED 
ItemEvent.SELECTED 
The ItemEvent.getItem() method is used to retrieve the actual selected item.


Previous | Next | Top
Last Modified November 4, 1997
Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu