Java Reference
In-Depth Information
Figure 13.6
The button changes size as the radio buttons are selected.
Swing Radio Buttons
Swing radio buttons are created using the javax.swing.JRadioButton and
javax.swing.ButtonGroup classes. The JRadioButton class has several con-
structors that take in a variation of the following parameters:
String label.
For the label of the radio button.
Icon icon.
For an icon associated with the radio button.
boolean selected.
For denoting the initial state of the radio button.
The ButtonGroup class only has one constructor:
public ButtonGroup().
Creates a new ButtonGroup object.
To create a Swing group of radio buttons, you instantiate a ButtonGroup
object, instantiate the JRadioButton objects, and pass each JRadioButton in to
the following ButtonGroup method:
public void add(AbstractButton button).
Adds the given button to the
ButtonGroup object.
The AbstractButton class in the javax.swing package is the common
parent class for JButton, JCheckBox, and JRadioButton. This means that in
Swing you can create a ButtonGroup of buttons, check boxes, and radio
buttons, although radio buttons are the most common use of the
ButtonGroup class.
The following JRadioButtonDemo program is similar to the RadioButton-
Demo program, except that it uses Swing components. The event handling
needed some slight modifications also, which are shown in the SwingChange-
Size class that is available on the Web site.