Previous | Next | Trail Map | Creating a User Interface | 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". 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 box.) Other good ways of providing groups of items the user can select are choices, lists, and menus.

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).

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; //independent checkboxes
Checkbox cb4, cb5, cb6; //only one of these three can be selected
CheckboxGroup cbg;

cb1 = new Checkbox();
cb1.setLabel("Checkbox 1");
cb2 = new Checkbox("Checkbox 2");
cb3 = new Checkbox("Checkbox 3");
cb3.setState(true);

. . .

cbg = new CheckboxGroup();
cb4 = new Checkbox("Checkbox 4", cbg, false);
cb5 = new Checkbox("Checkbox 5", cbg, false);
cb6 = new Checkbox("Checkbox 6", cbg, false);
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 | Using Components, the GUI Building Blocks