Checkboxes and Radio Buttons
A checkbox is a labeled toggle switch. Each time the user clicks it, its state toggles between checked and unchecked. Swing implements the checkbox as a special kind of button. Radio buttons are similar to checkboxes, but they are normally used in groups. Clicking on one radio button in the group automatically turns the others off. They are named for the mechanical preset buttons on old car radios (like some of us had in high school).
Checkboxes and radio buttons are represented by instances of
JCheckBox and JRadioButton,
respectively. Radio buttons can be tethered together using an instance of
another class called ButtonGroup . By now
you’re probably well into the swing of things (no pun intended) and could
easily master these classes on your own. We’ll use an example to
illustrate a different way of dealing with the state of components and to
show off a few more things about containers.
A JCheckBox sends ItemEvents when it’s pushed. Because a checkbox
is a kind of button, it also fires ActionEvents when checked. For something like a
checkbox, we might want to be lazy and check on the state of the buttons
only at some later time, such as when the user commits an action. For
example, when filling out a form you may only care about the user’s
choices when the submit button is finally pressed.
The next application, DriveThrough, lets us check off selections on a
fast food menu, as shown in Figure 17-3.
Figure 17-3. The DriveThrough application
DriveThrough ...