Using Components, the GUI Building Blocks |
The Checkboxclass 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 CheckboxGroupobject 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 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.
Besides the Checkbox methods shown above, Checkbox has two additional methods you might want to use: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);getCheckboxGroup()
andsetCheckboxGroup()
. Besides the single CheckboxGroup constructor used in the code example, CheckboxGroup also defines the following methods:getCurrent()
andsetCurrent()
. These methods get and set (respectively) the current selected Checkbox.
Using Components, the GUI Building Blocks |