Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks

How to Use Choices

The Choice(in the API reference documentation) class provides a menu-like list of choices, accessed by a distinctive button. The user presses the button to bring up the "menu", and then chooses one of the items. When the user chooses an item, the Choice generates an action event.

Choices are useful when you need to display a number of alternatives in a limited amount of space, and the user doesn't need to see all the alternatives all the time. Another name you might know for this UI element is pop-up list. Other ways of providing multiple alternatives are checkboxes, lists, and menus.

Below is an applet that has a Choice and a Label. When the user chooses an item from the Choice list, the Label changes to reflect the item chosen. Note that the index of the first item in the Choice is 0.


Your browser doesn't understand the <APPLET> tag, so here are some snapshots of choices.

Here's what this page's applet looks like at first:

Here's what the applet looks like as you select another choice item ("san"):
Finally, here's what the applet looks like after "san" is selected:


Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go to example-1dot1/ChoiceDemo.html.

Below is the code that creates the Choice and handles events from it. (Here's the whole program.) Note that the second parameter to the action() method (which is the same as e.arg), is the string from the selected item.

    //...Where instance variables are defined:
    Choice choice; //pop-up list of choices

    //...Where initialization occurs:
    choice = new Choice();
    choice.addItem("ichi");
    choice.addItem("ni");
    choice.addItem("san");
    choice.addItem("yon");
    label = new Label();
    setLabelText(choice.getSelectedIndex(), choice.getSelectedItem());

. . .

public boolean action(Event e, Object arg) {
    if (e.target instanceof Choice) {
            setLabelText(choice.getSelectedIndex(), (String)arg);
            return true;
        }
        return false;
    }
}
Besides the methods used above, the Choice class defines these other useful methods:
int countItems()
Returns the number of items in the choice.
String getItem(int)
Returns the String displayed by the item at the specified index.
void select(int)
Selects the item at the specified index.
void select(String)
Selects the item that's displaying the specified String.


Previous | Next | Trail Map | Creating a User Interface | Using Components, the GUI Building Blocks