What is Java Choice with Example?

Java comes with many GUI components placed in java.awt package. One component is Java Choice (in other GUI technologies, it is known as combo box).

1. What is Java Choice component?
2. When to use Choice?

Choice is replacement to radio buttons. When radio buttons are many to display, they flock all the frame. As an alternative, the java.awt package comes with Choice. That is, Choice is meant for single selection only.

3. How Choice component looks?

Choice gives a dropdown list of items from which user can select only one. When selected, the dropdown list disappears displaying the selected item.

4. What event Choice generates and the listener that handles?

Choice generates ItemEvent and is handled by ItemListener.

5. How to know which item user selected in Choice?

Choice class comes with two methods – getSelectedItem() returning the item selected by the user as a string and getSelectedIndex() returning the item index number selected by the user as an integer value. The first item added to Choice gets 0 index number by default.

Following is a simple program on Java Choice component (a big program we see later) to get the concept. User selection is displayed at DOS prompt for simplicity.
import java.awt.*;
import java.awt.event.*;

public class SimpleChoiceExample extends Frame implements ItemListener
{
  Choice fruits;			// reference variable
  public SimpleChoiceExample()
  {				        // first set the layout to frame
    setLayout(new FlowLayout());
				        // create Choice component; convert reference variable into object
    fruits = new Choice();
				        // add some items to Choice
    fruits.addItem("Apple");		// gets index number by default as 0
    fruits.addItem("Guava");		// gets index number by default as 1 and so on other items
    fruits.addItem("Pine Apple");
    fruits.addItem("Mango");
				        // link ItemListener
    fruits.addItemListener(this);	// "this" refers ItemListener

   add(fruits);			        // add Choice to frame

    setTitle("Choice Simple Example");
    setSize(300, 200);
    setVisible(true);  
  }
  	                                // override the only abstract method of ItemListener
  public void itemStateChanged(ItemEvent e)
  {
    String str = fruits.getSelectedItem();         // returns the selected item as a string
    int num = fruits.getSelectedIndex();           // returns the selected item as a integer

    System.out.println("You like " + str + " of serial number " + (num+1));
  }
  public static void main(String args[])
  {
    new SimpleChoiceExample();
  }


Java Choice
Output screenshot on Java Choice Example

Generally in menu cards, the serial number starts with 1 and not with 0. For this reason, num+1 is given.

A big program with full explanation with screen shot is given at Java AWT Choice – Replacement to Radio Buttons

Leave a Comment

Your email address will not be published.