Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using Components, the GUI Building Blocks

How to Use Checkboxes

The Checkbox(in the API reference documentation) class provides checkboxes -- two-state buttons that can be either "on" or "off". When the user clicks a checkbox, the checkbox state changes and it generates an action event. Other ways of providing groups of items the user can select are choices, lists, and menus.

If you want a group of checkboxes in which only one checkbox at a time can be "on", you can add a CheckboxGroup(in the API reference documentation) object to oversee the state of the checkboxes. (You might know this UI element as a radio button.)

Below is an applet that has two columns of checkboxes. On the left are three independent checkboxes. You can select all three of the checkboxes, if you like. On the right are three checkboxes that are coordinated by a CheckboxGroup object. The CheckboxGroup ensures that no more than one of its checkboxes is selected at a time. To be specific, a checkbox group can come up with no checkboxes selected, but once the user selects a checkbox, exactly one of the checkboxes will be selected forever after.

Here's how the applet looks when it first comes up:

Here's how the applet looks after the user clicks Checkbox 1, Checkbox 2, Checkbox 2 (again), and then Checkbox 4, Checkbox 5, and Checkbox 5 (again).


Note: Because this applet doesn't define an event handler, its code compiles cleanly in both 1.0 and 1.1.

Here's the whole program. Below is the code that creates both groups of checkboxes. Note that only the second, mutually-exclusive group of checkboxes is controlled by a CheckboxGroup.

Panel p1, p2;
Checkbox cb1, cb2, cb3; //These are independent checkboxes.
Checkbox cb4, cb5, cb6; //These checkboxes are part of a group.
CheckboxGroup cbg;

cb1 = new Checkbox();   //Default state is "off" (false).
cb1.setLabel("Checkbox 1");
cb2 = new Checkbox("Checkbox 2");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true);     //Set state to "on" (true).
. . .
cbg = new CheckboxGroup();
cb4 = new Checkbox("Checkbox 4", cbg, false); //initial state: off (false)
cb5 = new Checkbox("Checkbox 5", cbg, false); //initial state: off
cb6 = new Checkbox("Checkbox 6", cbg, false); //initial state: off
Besides the Checkbox methods shown above, Checkbox has two additional methods you might want to use: getCheckboxGroup() and setCheckboxGroup(). Besides the single CheckboxGroup constructor used in the code example, CheckboxGroup also defines the following methods: getCurrent() and setCurrent(). These methods get and set (respectively) the current selected Checkbox.


Previous | Next | Trail Map | Creating a User Interface (with Swing) | Using Components, the GUI Building Blocks