Java Reference
In-Depth Information
The
saveFormat
object is used to group together the
s1
and
s2
radio buttons. The
s2
object, which has the label
“XML”
, is selected. Only one member of the group can be
selected at a time—if one component is selected, the
ButtonGroup
object makes sure that
all others in the group are deselected.
Listing 9.6 contains an application with four radio buttons in a group.
LISTING 9.6
The Full Text of
FormatFrame.java
1: import javax.swing.*;
2:
3: public class FormatFrame extends JFrame {
4: JRadioButton[] teams = new JRadioButton[4];
5:
6: public FormatFrame() {
7: super(“Choose an Output Format”);
8: setSize(320, 120);
9: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10: teams[0] = new JRadioButton(“Atom”);
11: teams[1] = new JRadioButton(“RSS 0.92”);
12: teams[2] = new JRadioButton(“RSS 1.0”);
13: teams[3] = new JRadioButton(“RSS 2.0”, true);
14: JPanel panel = new JPanel();
15: JLabel chooseLabel = new JLabel(
16: “Choose an output format for syndicated news items.”);
17: panel.add(chooseLabel);
18: ButtonGroup group = new ButtonGroup();
19: for (int i = 0; i < teams.length; i++) {
20: group.add(teams[i]);
21: panel.add(teams[i]);
22: }
23: add(panel);
24: setVisible(true);
25: }
26:
27: public static void main(String[] arguments) {
28: FormatFrame ff = new FormatFrame();
29: }
30: }
9
Figure 9.5 shows the application running. The four
JRadioButton
objects are stored in
an array, and in the
for
loop in lines 19-22 each element is first added to a button group
and then added to a panel. After the loop ends, the panel is used for the application's
content pane.