next up previous contents
Next: CheckBoxPanel.java Up: Some examples of event-driven Previous: ButtonFrame.java   Contents

Checkbox

A checkbox is a button with a one-bit state--a checkbox is either ``selected'' or ``not selected''. In Swing, the basic checkbox class is JCheckBox. Like a button, there is only one action that a user can perform on a checkbox--to click on it. Thus, in Java the listener for JCheckBox is the same as that for JButton--ActionListener. Clicking a checkbox toggles its state. We use the method isSelected() to determine the current state of a JCheckBox.

In CheckBoxPanel.java below, we define a JPanel with two checkboxes. The panel CheckBoxPanel serves as an ActionListener for both its checkboxes. When a checkbox is clicked, it examines the state of both checkboxes to determine which colour to paint the background.

As with ButtonPanel, we have to embed CheckBoxPanel in a JFrame, called CheckBoxFrame below, in order to display it. There is no real difference between the code for CheckBoxFrame and ButtonFrame which we have seen earlier.

Finally, we have a main program that creates and displays a CheckBoxFrame.



Subsections

Madhavan Mukund 2004-04-29