Java Reference
In-Depth Information
12.9 Radio Buttons
Radio buttons are similar to check boxes because they can be either checked or
unchecked. However, there are two major differences. First, unlike check boxes, radio but-
tons are round. Second, radio buttons are usually logically placed inside the same button
group. Only one radio button can be selected at any time inside a button group. When
a radio button is pressed, the last radio button in the button group that was selected is
deselected. To see how radio buttons work, here is a very simple program.
import
java .awt .
∗
;
import
javax . swing .
∗
;
public class
Test
{
public static void
main(String [] args)
{
NumbersFrame f =
new
NumbersFrame () ;
f . setVisible(
true
);
}
}
class
NumbersFrame
extends
JFrame
{
public
NumbersFrame ()
{
setSize (400,100) ;
JPanel p =
new
JPanel () ;
a d d ( p , B o r d e r L a y o u t . NORTH) ;
JRadioButton upButton =
new
JRadioButton(
"Increment"
,
true
);
JRadioButton downButton =
new
JRadioButton(
"Decrement"
,
false
);
p. add(upButton) ;
p . add(downButton) ;
ButtonGroup group =
new
ButtonGroup () ;
group .add(upButton) ;
group .add(downButton) ;
}
}
The program's window is shown in Figure 12.6. Note that the text field in the figure will
be added in the next section. The constructor of the
JRadioButton
class takes as input the
name of the button and a Boolean variable that specifies if the button is initially selected.
Note that at most one radio button in the group can be initially selected.
There is no
J
before the name of the
ButtonGroup
class. The reason is that this is
a logical class and is not part of the Swing library. The
add
method is used to add radio
buttons to a button group. In every button group, at most one radio button can be selected.
Note that if the button group was not created and the radio buttons added to it, then both
the
Increment
and
Decrement
radio buttons could be selected at the same time. If you run
the program, you will see that only one radio button in the group can be selected at any
given time.