The Choice component is a combination of textfield and drop down list of items. User can make selection by clicking at an item from the list or by typing into the box. Note that you cannot select multiple items from the list. This component is the best component to use than the check box groups or list because it consumes less space than these components. It can be created by instantiating the Choice class. Choice has only one default constructor, namely the following.
Choice choice = new Choice()
To add items to the choice created in the above statement, the following methods can be used.
choice.addltem(String str);
choice.add(String str);
To get the selected item, the method getSelectedltem is used and the index of the selected item can be obtained using the method getSelectedlndex. Items can also be selected using select(int index) and select(String name) when either the index or the name of the item is known.
Choice Interface
Method | Returns | Notes |
Choice() |
| Creates an empty choice box; use addItem() to populate |
addItem(String item) | Void |
|
countItems() | Int | Useful for interrogating the Choice contents |
getItem(int index) | String | From 0 to countItems() -1 |
getSelectedIndex() | Int | Tells which item is selected by number |
getSelectedItem() | String | Returns the selected item’s text |
select(int pos) | Void | Make a particular cell the default |
select(String str) | Void | Highlight the first cell with text equal to str |
import java.awt.*;
class ChoiceExample extends Frame
{
ChoiceExample()
{
setLayout(new FlowLayout());
Label lblCourse = new Label("Course");
Label lblweekDay = new Label("Day");
Choice course = new Choice();
course.add("BCA");
course.add("MCA");
course.add("MBA");
String[] day={"Mon","Tue","wed","Thu","fri","Sat","Sun"};
Choice weekDay =new Choice();
for(int i=0;i<day.length; i++)
{
weekDay.add(day[i]);
}
add(lblCourse); add(course);
add(lblweekDay); add(weekDay);
}
}
class ChoiceJavaExample
{
public static void main(String args[])
{
ChoiceExample frame = new ChoiceExample();
frame.setTitle("Choice in Java Example");
frame.setSize(250,100);
frame.setResizable(false);
frame.setVisible(true);
}
}