Using Components, the GUI Building Blocks |
The Choice 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.
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 ase.arg
), is the string from the selected item.Besides the methods used above, the Choice class defines these other useful methods://...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; } }
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.
Using Components, the GUI Building Blocks |