Java JRadioButton

Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. They are supported by the JRadioButton class, which extends JToggleButton. JRadioButton provides several constructors:

JRadioButton(String str)

Here, str is the label for the button.

Example:
If a user presses a radio button that is in a group, any previously selected button in that group is automatically deselected. A button group is created by the ButtonGroup class. Its default constructor is invoked for this purpose. Elements are then added to the button group via the following method:

void add(AbstractButton ab)

Here, ab is a reference to the button to be added to the group.

A JRadioButton generates action events, item events, and change events each time the button selection changes. Most often, it is the action event that is handled, which means that you will normally implement the ActionListener interface. Recall that the only method defined by ActionListener is actionPerformed(). Inside this method, you can use some different ways to determine which button was selected. First, you can check its action command by calling getActionCommand().

By default, the action command is the same as the button label, but you can set the action command to something else by calling setActionCommand() on the radio button. Second, you can call getSource() on the ActionEvent object and check that reference against the buttons. Finally, you can simply check each radio button to find out which one is currently selected by calling isSelected() on each button.

Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JApplet implements ActionListener
{
JLabel jlab;
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch (Exception exc)
{
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI()
{
setLayout(new FlowLayout());
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
add(b3);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
jlab = new JLabel("Select One");
add(jlab);
}
public void actionPerformed(ActionEvent ae)
{
jlab.setText("You selected " + ae.getActionCommand());
}
}