AWT Choice

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java AWT Choice

The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration

  1. public class Choice extends Component implements ItemSelectable, Accessible  

Java AWT Choice Example

  1. import java.awt.*;  
  2. public class ChoiceExample  
  3. {  
  4.         ChoiceExample(){  
  5.         Frame f= new Frame();  
  6.         Choice c=new Choice();  
  7.         c.setBounds(100,10075,75);  
  8.         c.add("Item 1");  
  9.         c.add("Item 2");  
  10.         c.add("Item 3");  
  11.         c.add("Item 4");  
  12.         c.add("Item 5");  
  13.         f.add(c);  
  14.         f.setSize(400,400);  
  15.         f.setLayout(null);  
  16.         f.setVisible(true);  
  17.      }  
  18. public static void main(String args[])  
  19. {  
  20.    new ChoiceExample();  
  21. }  
  22. }  

Java AWT Choice Example with ActionListener

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. public class ChoiceExample  
  4. {  
  5.         ChoiceExample(){  
  6.         Frame f= new Frame();  
  7.         final Label label = new Label();          
  8.         label.setAlignment(Label.CENTER);  
  9.         label.setSize(400,100);  
  10.         Button b=new Button("Show");  
  11.         b.setBounds(200,100,50,20);  
  12.         final Choice c=new Choice();  
  13.         c.setBounds(100,10075,75);  
  14.         c.add("C");  
  15.         c.add("C++");  
  16.         c.add("Java");  
  17.         c.add("PHP");  
  18.         c.add("Android");  
  19.         f.add(c);f.add(label); f.add(b);  
  20.         f.setSize(400,400);  
  21.         f.setLayout(null);  
  22.         f.setVisible(true);  
  23.         b.addActionListener(new ActionListener() {  
  24.             public void actionPerformed(ActionEvent e) {       
  25.          String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());  
  26.          label.setText(data);  
  27.         }  
  28.         });           
  29.         }  
  30. public static void main(String args[])  
  31. {  
  32.    new ChoiceExample();  
  33. }  
  34. }