Differentiate between Choice class and List class in AWT with suitable description and example.
Choice Class
Choice control is used to show the popup menu of choices. The selected choice is shown at the top of the menu. Thus, a Choice control is a form of a menu. When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made.
or,
The object of the Choice class is used to show the popup menu of choices. Choice selected by the user is shown on the top of a menu. It inherits the Component class.
Commonly used Constructors
Choice(); //Creates a new choice menu.
AWT Choice Class Declaration
public class Choice extends Component implements ItemSelectable, Accessible
Commonly used Public Methods
void add(String item); //Adds an item to this Choice menu.
String getItem(int index)://Gets the string at the specified index in this Choice menu.
int getItemCount();//Returns the number of items in this Choice menu.
int getSelectedIndex(); //Returns the index of the currently selected item.
String getSelectedItem(); //Gets a representation of the current choice as a string.
void remove(int position);//Removes an item from the choice menu at the specified position.
void removeAll()://Removes all items from the choice menu.
void select(int pos)://Sets the selected item in this Choice menu to be the item at the specified position.
void select(String str); //Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.
Java AWT Choice Example
In the following example, we are creating a choice menu using Choice() constructor. Then we add 5 items to the menu using add() method and Then add the choice menu into the Frame.
ChoiceExample1.java
// importing awt class
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// creating a choice component
Choice c = new Choice();
// setting the bounds of choice menu
c.setBounds(100, 100, 75, 75);
// adding items to the choice menu
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
// adding choice menu to frame
f.add(c);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
Comments
Post a Comment