Java Reference
In-Depth Information
The following CheckboxDemo program creates a GUI with four check
boxes. The item events are handled by the MixColors class, which can be
found on the Web site. Study the CheckboxDemo program carefully, then try
to determine how the GUI looks, and what the event handler is doing to the
window.
import java.awt.*;
public class CheckboxDemo extends Frame
{
private Checkbox red, yellow, blue;
public CheckboxDemo(String title)
{
super(title);
red = new Checkbox(“Red”);
blue = new Checkbox(“Blue”);
yellow = new Checkbox(“Yellow”);
//add the checkboxes to the frame
Panel north = new Panel();
north.add(red);
north.add(blue);
north.add(yellow);
this.add(north, BorderLayout.NORTH);
//register the event listener
MixColors listener = new MixColors(this);
red.addItemListener(listener);
blue.addItemListener(listener);
yellow.addItemListener(listener);
}
public static void main(String [] args)
{
Frame f = new CheckboxDemo(“CheckboxDemo”);
f.setSize(300,300);
f.setVisible(true);
}
}
The MixColors listener uses the getItem() method of ItemEvent to deter-
mine which check box generated the event. It then uses getStateChange() to
determine if the check box was selected or deselected. The three booleans in
MixColors represent the three check boxes in the GUI, and the color of the win-
dow is determined by which check boxes are selected.
For example, selecting red causes the window to be red. Selecting red and
yellow causes the window to be orange. Selecting blue and yellow makes it
green, blue and red makes it purple, and so on. A sample output is shown in
Figure 13.4.
Search WWH ::




Custom Search