Java Reference
In-Depth Information
The ChoiceDemo program (see the Web site for this topic for a complete list-
ing) is similar to the ListDemo program, except that the items appear in a
Choice, created using the following code.
items = new Choice();
items.add(“”);
items.add(“Sunday”);
items.add(“Monday”);
items.add(“Tuesday”);
items.add(“Wednesday”);
items.add(“Thursday”);
items.add(“Friday”);
items.add(“Saturday”);
The following event handler ShowChoice is an ItemListener that displays
the currently selected item in a Label. Study the program and try to determine
how it works. Figure 13.12 shows the output.
import java.awt.*;
import java.awt.event.*;
public class ShowChoice implements ItemListener
{
private Label display;
public ShowChoice(Label d)
{
display = d;
}
public void itemStateChanged(ItemEvent a)
{
Object source = a.getSource();
if(!(source instanceof Choice))
{
return;
}
Choice list = (Choice) source;
String selected = list.getSelectedItem();
display.setText(selected);
}
}
Figure 13.12
Output of the ChoiceDemo program.
Search WWH ::




Custom Search