Choice
Home Up Button Checkbox CheckboxGroup Choice Key List Menu Mouse Popup Window Text

 

A "Choice" component is a drop-down list.  A drop-down list only shows the currently selected choice unless the component is clicked on, at which time all of the choices are shown.  Experiment with the applet below to see what it does.  Then proceed to understand the code that generates the applet.

You would see an applet here if your browser supported Java.

The applet implements the "ItemListener" interface, requiring it to implement an "itemStateChanged" method (see the event handling reference).

The "init" method sets the layout manager to be the null layout manager.  It then creates a "Choice" component named "colorChoice" and adds "red" and "blue" as possible choices to this component.  Since the null layout manager is being used, "colorChoice" must be located and sized with the "setBounds" method.  Then an item listener is added so that events involving this component can be detected.  Finally, "colorChoice" is added to the display surface.

The "itemStateChanged" method uses the "getItem" method to find out which choice was selected.  The background color of the display window is set to the appropriate color.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;            
public class Example extends Applet implements ItemListener
{
	public void init ()
	{
		setLayout(null);            
		Choice colorChoice = new Choice();            
		colorChoice.add("red");
		colorChoice.add("blue");            
		colorChoice.setBounds(100, 100, 100, 50);  
		colorChoice.addItemListener(this);
		add(colorChoice);
}            
	public void itemStateChanged (ItemEvent evt)
	{            
		if (evt.getItem().equals("red"))
			setBackground (Color.red);
		else if (evt.getItem().equals("blue"))
			setBackground (Color.blue);      
		repaint();            
	}            
}