Java's Basic User Interface Components - The Choice List Class
(Page 7 of 10 )
Choice Lists, which is created from the Choice class, are components that enable a single item to be picked from a pull-down list. We encounter this control very often on the web when filling out forms. The first step in creating a Choice List is to create a choice object to hold the list, as shown below:
Choice cgender = new Choice();Items are added to the Choice List by using addItem(String) method on the object. The following code adds two items to the gender choice list.
cgender.addItem(“Female”); cgender.addItem(“Male”);After you add the Choice List it is added to the container like any other component using the add() method. The following example shows an Applet that contains a list of shopping items in the store.
/*
<Applet code= “ChoiceTest.class”
Width = 200
Height = 150>
</applet>
*/
Import java.awt.*;
Public class ChoiceTest extends java.applet.Applet
{
Choice shoplist = new Choice();
Public void init(){
shoplist.addItem(“Bed And Bath”);
shoplist.addItem(“Furniture”);
shoplist.addItem(“Clothing”);
shoplist.addItem(“Home Appliance”);
shoplist.addItem(“Toys and Accessories”);
add(shoplist);
}
}
The choice list class has several methods, which are given below:
| Method | Action |
| getItem() | Returns the string item at the given position (items inside a choice begin at 0, just like arrays) |
| countItems() | Returns the number of items in the menu |
| getSelectedIndex() | Returns the index position of the item that's selected |
| getSelectedItem() | Returns the currently selected item as a string |
| select(int) | Selects the item at the given position |
| select(String) | Selects the item with the given string |
Next: The TextField and TextArea Class >>
More Java Articles
More By Gayathri Gokul