- Details
- Written by Nam Ha Minh
- Last Updated on 06 July 2019   |   Print Email
Table of content- Creating new JRadioButtion components
- Grouping the radio buttons together
- Adding the radio buttons to a container
- Getting and setting selected state
- Adding action listener
- Customizing appearance
- A Swing demo program for JRadioButton
JRadioButtonis a Swing component that represents an item with a state selected or unselected. Usually a group of radio buttons is created to provide options to the user, but only one option can be selected at a time. The following screenshot show a group of three radio buttons placed on a
JFrame:Here’s the code to create a simple program above:
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class SwingJRadioButtonDemo extends JFrame {
public SwingJRadioButtonDemo() {
super("Swing JRadioButton Demo");
JRadioButton option1 = new JRadioButton("Linux");
JRadioButton option2 = new JRadioButton("Windows");
JRadioButton option3 = new JRadioButton("Macintosh");
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
setLayout(new FlowLayout());
add(option1);
add(option2);
add(option3);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingJRadioButtonDemo().setVisible(true);
}
});
}
}
Let’s look at other common practices when working with the
JRadioButton component.
1. Creating new JRadioButtion components
There are several ways to construct a new
JRadioButton, but the most common way is to pass some text to its constructor, for example:
JRadioButton optionLinux = new JRadioButton("Linux");
In addition to the text that tells what the option is for, it’s possible to specify an icon and selected state in any combination of [text, icon, selected]. Here are some examples:
JRadioButton optionWin = new JRadioButton("Windows", true);
Of course we can set the text and selected state for a radio button after it is created, for example:
optionWin.setText("Windows");
optionWin.setSelected(true);
We can also pass an instance of a class that implements the
javax.swing.Action interface when creating a radio button. Using an
Action is useful in case we have multiple components that share same properties and state like a menu item, a check box, a button, etc. Here’s an example that creates a radio button with caption “Macintosh” and selected state:
Action action = new CommonAction("Macintosh", true);
JRadioButton optionMac = new JRadioButton(action);
Where the
CommonAction class is declared as follows:
class CommonAction extends javax.swing.AbstractAction {
public CommonAction(String text, boolean selected) {
super(text);
super.putValue(SELECTED_KEY, selected);
}
@Override
public void actionPerformed(ActionEvent event) {
// code to handle click event goes here...
}
}
This class extends the abstract class
AbstractAction which in turn, implements the
javax.swing.Action interface. The
AbstractAction class already implements standard behaviors from the
Action interface, so our subclass can focus on implementing action event or setting other attributes if necessary (the selected state, in this case).
2. Grouping the radio buttons together
Because a typical behavior of radio buttons is only one button can be selected, so we should put all related radio buttons into a group by using the
javax.swing.ButtonGroup class as follows:
ButtonGroup group = new ButtonGroup();
group.add(optionLinux);
group.add(optionWin);
group.add(optionMac);
The
ButtonGroup class is responsible to make sure only one button is selected (by deselecting others in the group). For example, in the following screenshot, the button “Windows” is selected:
If we don’t put the radio buttons into a group, then each button can be selected independently, for example:
Remember that the
ButtonGroup class just creates a logical group of radio buttons, not a physical one. That means the physical position of the buttons is not affected.
3. Adding the radio buttons to a container
Like other Swing components, the radio buttons are usually added to a container like a
JPanel or
JFrame using the
add() method, but there will be different ways depending on which layout manager used by the container. Here are some examples:
- Adding the radio buttons to a JFrame with FlowLayout manager:
theFrame.setLayout(new FlowLayout());
theFrame.add(optionLinux);
theFrame.add(optionWin);
theFrame.add(optionMac);
- Adding the radio buttons to a JPanel with BorderLayout manager:
JPanel panel = new JPanel(new BorderLayout());
panel.add(optionLinux, BorderLayout.NORTH);
panel.add(optionWin, BorderLayout.CENTER);
panel.add(optionMac, BorderLayout.SOUTH);
- Adding the radio buttons to a JPanel with GridBagLayout manager:
JPanel panel = new JPanel(new GridBagLayout());
// specify constraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
panel.add(optionLinux, constraints);
constraints.gridx = 1;
panel.add(optionWin, constraints);
constraints.gridx = 2;
panel.add(optionMac, constraints);
4. Getting and setting selected state of JRadioButton
A typical usage of radio button is checking its selected state, using the
isSelected() method, for example:
boolean isLinuxSelected = optionLinux.isSelected();
if (isLinuxSelected) {
// the Linux option is selected
} else {
// the Linux option is deselected
}
And to set a radio button’s selected state, use the
setSelected() method, for example:
// set the option Windows is selected
optionWin.setSelected(true);
// set option Macintosh is deselected
optionMac.setSelected(false);
5. Adding action listener for JRadioButton
Like Swing’s
JButton component, a radio button can receive clicking event when the user selects it. We can use the
addActionListener() method to specify an action listener for the radio button, for example:
optionLinux.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
// do something when the button is being selected...
}
});
The radio button fires an
ActionEvent whenever the user clicks on it, even if the radio button is selected before. If you just want to care about when a radio button’s state changes (selected or deselected), use an
ItemListener as follows:
optionLinux.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent event) {
int state = event.getStateChange();
if (state == ItemEvent.SELECTED) {
// do something when the button is selected
} else if (state == ItemEvent.DESELECTED) {
// do something else when the button is deselected
}
}
});
It’s recommended to use a same action listener for a group of related radio button, as shown in the following example:
RadioButtonActionListener actionListener = new RadioButtonActionListener();
optionLinux.addActionListener(actionListener);
optionWin.addActionListener(actionListener);
optionMac.addActionListener(actionListener);
6. Customizing appearance for JRadioButton
Set foreground color, background color, font style and tooltip text for a radio button:
optionLinux.setForeground(Color.BLUE);
optionLinux.setBackground(Color.YELLOW);
optionLinux.setFont(new java.awt.Font("Tahoma", Font.BOLD, 16));
optionLinux.setToolTipText("Select this option if you like Linux");
Screenshot:
7. A Swing demo program for JRadioButton
For your reference, we created the following demo program:
When a radio button is clicked, an appropriate image will be shown. If the
OK button is clicked, a message dialog appears saying the selected option:
You can download full source code as well as executable jar file of this program under Attachments section.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.