Java Choice Replacement Radio Buttons

Choice, another GUI component from the toolkit of classes of java.awt. Choice presents a pull-down menu. Choice is a replacement to radio buttons. Choice is chosen when radio buttons are many to display. Choice is popularly known as Combo box in other GUI environments. Choice, like radio buttons, allows selecting only one option among many. Choice occupies less space on the container than many radio buttons doing the same job. Many radio buttons flock the whole container and in this case alternative to the programmer is Choice. When the user selects some item, the current selected item is displayed and the drop down list disappears.

Choice generates ItemEvent and handled by ItemListener. Following is the class signature of Choice component.

public class Choice extends Component implements ItemSelectable, Accessible

This is the second program developed as an applet instead of frame; the first one being radio buttons. This attempt is only for practicing applets with GUI.

Example on Java Choice Replacement Radio Buttons
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

public class VisitingPlaces extends Applet implements ItemListener
  Choice visit;
  TextField tf;
  String states[] = { "Tamilnadu", "Karnataka", "Andhra Pradesh", "Kerala", "Maharashtra" };
  public void init()
  {                            // set the layout
    setLayout(new BorderLayout());
                               // create the components
    visit = new Choice();
    tf = new TextField(15);
                               // populate the Choice
                            // learning some more methods
    visit.insert("Hyderabd", 2);"Kochi");
                           // register with the listener
                           // add the components to applet
    add(visit, BorderLayout.NORTH);
    add(tf, BorderLayout.SOUTH);
  public void paint(Graphics g)
    g.drawString("No. of items: " + visit.getItemCount(), 50, 150);
    g.drawString("Item at 2nd index number: " + visit.getItem(2), 50, 170);
   public void itemStateChanged(ItemEvent e)
   {              // get the item selected by the user
     String str = visit.getSelectedItem();
     int x = visit.getSelectedIndex();
                  // dispaly in the text field
     tf.setText("U go to " + str + " of state " + states[x]);

HTML file to run the above applet
FileName: Visit.html


Java Choice Replacement Radio Buttons
Output of Java Choice Replacement Radio Buttons

3 thoughts on “Java Choice Replacement Radio Buttons”

Leave a Comment

Your email address will not be published.