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 usually arranged in groups. Click on one radio button in the group, and the others automatically turn off. They are named for the preset buttons on old car radios.
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
ItemEvent
s when it’s pushed. Since a checkbox
is a kind of button, it also fires
ActionEvent
s when it
becomes 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. It’s like filling out
a form; you can change your choices until you submit the form.
The following application, DriveThrough, lets us
check off selections on a fast food menu, as shown in Figure 14.1. DriveThrough prints
the results when we press the Place
Order button. Therefore, we can ignore all the events generated ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access