In this tutorial

You will learn how to...
  • How to create a JRadioButton.
  • How to group RadioButtons together.
  • How to find which RadioButton is selected.

JRadioButton - Part 1

JRadioButtons are just as easy as the rest. Radio Buttons as you may have met before are another way of selecting from a list. Unlike Checkboxes though, you can only choose one from the list.

I don't want to bore you guys and girls, so let's get right into the example. In this example, I've decided to create a brand new example! Woo! Luckily, there will still be coloured boxes on the page for all you box-fans.

Down the left-hand side of the GUI will be the RadioButtons which will let you choose what to display.
The CardLayout Panel will deal with what is displayed in the middle.
This example will show the different alignments you can use in a FlowLayout! Crazy!

(PS. Instead of creating a new Panel for each Alignment, we could have just used mainPanel.setAlignment() to change the positioning. However, this would not let you see how to use the show() command in the CardLayout!)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import javax.swing.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

public class RadioButtonExample implements  ActionListener{

    JRadioButton leadingButton, centerButton, trailingButton;
    JPanel cardPanel;
    String names[] = {"LEADING", "CENTER", "TRAILING"};

    public JPanel createContentPane (){
        
        JPanel totalGUI = new JPanel();
        
        // First, lets get on with creating the RadioButtons.
        // We create each RadioButton, then add it to a ButtonGroup.
        // This ButtonGroup deals with keeping only one selected.
        // We must also add them to a JPanel to display the RadioButtons.
        
        leadingButton = new JRadioButton(names[0]);
        leadingButton.addActionListener(this);
        leadingButton.setSelected(true);
        centerButton = new JRadioButton(names[1]);
        centerButton.addActionListener(this);
        trailingButton = new JRadioButton(names[2]);
        trailingButton.addActionListener(this);
        
        // Create the button group to keep only one selected.
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(leadingButton);
        btnGroup.add(centerButton);
        btnGroup.add(trailingButton);
        
        // Create the JPanel to display the RadioButtons.
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS));
        
        buttonPanel.add(Box.createRigidArea(new Dimension(10,10)));
        buttonPanel.add(leadingButton);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(centerButton);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(trailingButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(10,10)));
        
        // We create the first JPanel with the FlowLayout.
        // Although we could just use ONE Panel and simply change the 
        // align using .setAlignment(), this way we can use CardLayout again.
        
        JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
        mainPanel.setPreferredSize(new Dimension(200, 120));
        mainPanel.setBackground(Color.gray);
    
        JPanel red = createSquareJPanel(Color.red, 50);
        JPanel blue = createSquareJPanel(Color.blue, 50);
        JPanel green = createSquareJPanel(Color.green, 50);
        JPanel orange = createSquareJPanel(Color.orange, 50);
        JPanel yellow = createSquareJPanel(Color.yellow, 50);
    
        mainPanel.add(red);
        mainPanel.add(blue);
        mainPanel.add(green);
        mainPanel.add(orange);
        mainPanel.add(yellow);
        
        // Second Panel.

        JPanel mainPanel_2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        mainPanel_2.setPreferredSize(new Dimension(200, 120));
        mainPanel_2.setBackground(Color.gray);
    
        JPanel red_2 = createSquareJPanel(Color.red, 50);
        JPanel blue_2 = createSquareJPanel(Color.blue, 50);
        JPanel green_2 = createSquareJPanel(Color.green, 50);
        JPanel orange_2 = createSquareJPanel(Color.orange, 50);
        JPanel yellow_2 = createSquareJPanel(Color.yellow, 50);
    
        mainPanel_2.add(red_2);
        mainPanel_2.add(blue_2);
        mainPanel_2.add(green_2);
        mainPanel_2.add(orange_2);
        mainPanel_2.add(yellow_2);

        // Third Panel
        
        JPanel mainPanel_3 = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        mainPanel_3.setPreferredSize(new Dimension(200, 120));
        mainPanel_3.setBackground(Color.gray);
    
        JPanel red_3 = createSquareJPanel(Color.red, 50);
        JPanel blue_3 = createSquareJPanel(Color.blue, 50);
        JPanel green_3 = createSquareJPanel(Color.green, 50);
        JPanel orange_3 = createSquareJPanel(Color.orange, 50);
        JPanel yellow_3 = createSquareJPanel(Color.yellow, 50);
    
        mainPanel_3.add(red_3);
        mainPanel_3.add(blue_3);
        mainPanel_3.add(green_3);
        mainPanel_3.add(orange_3);
        mainPanel_3.add(yellow_3);
        
        // We create the CardPanel and give it plenty of padding.
        
        cardPanel = new JPanel(new CardLayout(50, 50));
        
        cardPanel.add(mainPanel, names[0]);
        cardPanel.add(mainPanel_2, names[1]);
        cardPanel.add(mainPanel_3, names[2]);

        // This sets the widgets on the screen to be layed out in a
        // top to bottom fashion with spacers inbetween.
        
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(buttonPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(20,0)));
        bottomPanel.add(cardPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        
        totalGUI.add(bottomPanel);
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // In this method, we create a square JPanel of a colour and set size
    // specified by the arguments.

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }

    // This actionPerformed simply takes sets the visibility of each
    // coloured box depending on what is selected on the combo box.

    public void actionPerformed(ActionEvent e) {

        // We need to get the current layout of the CardLayout panel
        // before we can change it.
        CardLayout cl = (CardLayout) (cardPanel.getLayout());

        if(e.getSource() == leadingButton)
        {
            cl.show(cardPanel, names[0]);
        }
        else if(e.getSource() == centerButton)
        {
            cl.show(cardPanel, names[1]);
        }
        else if(e.getSource() == trailingButton)
        {
            cl.show(cardPanel, names[2]);
        }
    }

    private static void createAndShowGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JRadioButtons [=]");

        RadioButtonExample demo = new RadioButtonExample();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
Again, we've gone ahead and just integrated the ActionListener. You all know what it is and what it does. If you have any confusion, go and have a look at the JButton tutorial.
Make sure you run the program and have a go, but it should look like this. Picture of a the RadioButtons

To instantiate the RadioButton, you pass a String as an argument for the auto-created Label. Without a string, no label occurs.
21
        leadingButton = new JRadioButton(names[0]);
RadioButtons use the ActionListener, so we add an ActionListener to detect any changes.
22
        leadingButton.addActionListener(this);
We should set one of the radio buttons to be selected at the start. Without this line, none of the radio buttons are selected at the start. Although this is not wrong per-se, it's a bit silly. We set the LEADING radio button to be selected at the start.
23
        leadingButton.setSelected(true);
RadioButtons need to belong to both a ButtonGroup and a JPanel. We add the RadioButtons to a ButtonGroup to make sure only one RadioButton from that group is selected at any time. Without the ButtonGroup, you can select all the radio buttons at once!
30
31
32
33
        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(leadingButton);
        btnGroup.add(centerButton);
        btnGroup.add(trailingButton);
To display them, we add the buttons to a JPanel. In this case it's a simple BoxLayout.
36
37
38
39
40
41
42
43
44
45
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS));
        
        buttonPanel.add(Box.createRigidArea(new Dimension(10,10)));
        buttonPanel.add(leadingButton);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(centerButton);
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(trailingButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(10,10)));
The only other segment of code that is new or different is the stuff in the actionPerformed() method.

As before we get the current CardLayout so we can change it. We change the CardLayout using the show() command.
The show() command shows the panel that has been instantiated with the String you pass in the argument. So if you use show(cardPanel, "LEADING"), the 'card' called "LEADING" set up at line 105 will be displayed.
151
            cl.show(cardPanel, names[0]);
Exercise

This is a very quick exercise. Take the code and run it. You will see that as you click one RadioButton, the previous one is deselected.
Now remove the buttons from the ButtonGroup (delete lines 30-33). Compile & Run, and try to click the RadioButtons again.
Take what you find to answer question 1!.

Questions

The hardest button to button.

Question 1. What to you get after running the program in the exercise?

  • a) None of the buttons appear.
  • b) You can select no buttons.
  • c) You can select all of the buttons.

Question 2. Why do we have a String as an argument?

  • a) To define the size.
  • b) To define the style.
  • c) To define the label.

Question 3. How do we set a button to be selected?

  • a) setSelected(true);
  • b) setSelected(false);
  • c) setSelected();




Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict