Choice is the GUI component which allows us to add 'n' number of items. This component allows selecting a single item at a time.
Creating a choice component is nothing but creating an object of Choice class.
choice ();
public void add (String); 71 public void addItem (String); 72 public void add (int pos, String); 73 public void addItem (int pos, String); 74 public String getSelectedItem (); 75 public int getSelectedIndex (); 76 public void remove (String); 77 public void remove (int); 78 public void removeAll (); 79 public void addItemListener (ItemListener); 710 public void removeItemListener (ItemListener); 711
Methods 1 and 2 are used for adding items to the choice component at end.
Methods 3 and 4 are used for adding the items at the specified position.
Methods 5 and 6 are used for obtaining the items either based on its name or on its index.
Methods 7 and 8 are used for removing the item of the choice component either based on its name or on its index (position).
Method 9 is used for removing all the items of choice components.
Methods 10 and 11 are used for registering and unregistering the events of choice components.
Write a java program which illustrates the concept of Choice?
Answer:
import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="ChoApp" height=300 width=300> </applet>*/ public class ChoApp extends Applet { Choice ch1, ch2; Label l1,l2; public void init () { setBackground (Color.yellow); setForeground (Color.red); l1=new Label ("AVAILABLE FONTS: "); l2=new Label ("REMOVED FONTS: "); ch1=new Choice (); ch2=new Choice (); add (l1); add (ch1); add (l2); add (ch2); GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment (); String f[]=ge.getAvailableFontFamilyNames (); for (int i=0; i<f.length; i++) { ch1.add (f [i]); } }// init () public void start () { ch1.addItemListener (new ch1 ()); } class ch1 implements ItemListener { public void itemStateChanged (ItemEvent ie); { if (ie.getSource ()==ch1) { String s1=ch1.getSelectedItem (); ch2.add (s1); ch1.remove (s2); } } }// ch1-inner class }// ChoApp class