JRadioButton: Selecting One Option from a Group in Java Swing

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SwingRadioButtonDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f1 = new JFrame("JRadioButton Demo");
            f1.setBounds(100, 100, 420, 260);
            f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f1.getContentPane().setLayout(null);

             // Create radio buttons:
            JRadioButton r1 = new JRadioButton("Option A (Male)", true);
            r1.setBounds(40, 30, 150, 30);
            f1.getContentPane().add(r1);

            JRadioButton r2 = new JRadioButton("Option B (Female)");
            r2.setBounds(40, 70, 150, 30);
            f1.getContentPane().add(r2);

             // Grouping ensures mutual exclusivity:
            ButtonGroup my_group = new ButtonGroup();
            my_group.add(r1);
            my_group.add(r2);

            JLabel l1 = new JLabel("Selected: Option A");
            l1.setBounds(40, 120, 250, 25);
            f1.getContentPane().add(l1);

             // Event listener:
            ActionListener listener = new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JRadioButton source = (JRadioButton) e.getSource();
                    l1.setText("Selected: " + source.getText());
                    System.out.println("Radio clicked: " + source.getText() + " | isSelected=" + source.isSelected());
                }
            };
            r1.addActionListener(listener);
            r2.addActionListener(listener);

            f1.setVisible(true);

             // Programmatic switch simulation:
            r2.doClick();
        });
    }
}

Terminal Output:

Radio clicked: Option B (Female) | isSelected=true
[GUI Window Rendered: 420x260, JRadioButton r1=false, r2=true, JLabel="Selected: Option B (Female)"]

1. Grouping Radio Buttons with ButtonGroup 🔝

In Java Swing, a JRadioButton by itself acts just like a toggle button. To ensure that selecting one option automatically unselects all other choices, you must add the radio buttons into a ButtonGroup:

ButtonGroup my_group = new ButtonGroup();
my_group.add(r1);
my_group.add(r2);

Make sure to import javax.swing.ButtonGroup; to avoid the compiler error "ButtonGroup cannot be resolved to a type".

2. Assigning and Reading Action Commands 🔝

Instead of inspecting each radio button individually with multiple if-else checks, assign an actionCommand code to each button and read the active code directly from group.getSelection():

import javax.swing.*;

public class ActionCommandRadioDemo {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("Credit Card");
        r1.setActionCommand("CC");
        JRadioButton r2 = new JRadioButton("PayPal", true);
        r2.setActionCommand("PP");

        ButtonGroup group = new ButtonGroup();
        group.add(r1);
        group.add(r2);

        String activeCode = group.getSelection().getActionCommand();
        System.out.println("Active Payment Method Code: " + activeCode);
    }
}

Terminal Output:

Active Payment Method Code: PP

3. Responding to State Changes with ItemListener 🔝

While ActionListener fires when a button is clicked, ItemListener fires whenever a button transitions between SELECTED and DESELECTED:

import java.awt.event.ItemEvent;
import javax.swing.JRadioButton;

public class ItemListenerRadioDemo {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("Dark Mode");
        r1.addItemListener(e -> {
            boolean selected = (e.getStateChange() == ItemEvent.SELECTED);
            System.out.println("ItemState changed: selected=" + selected);
        });
        r1.setSelected(true);
    }
}

Terminal Output:

ItemState changed: selected=true

4. Iterating Through All Buttons in a ButtonGroup 🔝

You can retrieve all buttons assigned to a group using group.getElements():

import java.util.Enumeration;
import javax.swing.*;

public class EnumerateGroupDemo {
    public static void main(String[] args) {
        ButtonGroup group = new ButtonGroup();
        group.add(new JRadioButton("Class Four"));
        group.add(new JRadioButton("Class Five", true));
        group.add(new JRadioButton("Class Six"));

        Enumeration<AbstractButton> elements = group.getElements();
        while (elements.hasMoreElements()) {
            AbstractButton btn = elements.nextElement();
            System.out.println("Group element: " + btn.getText() + " (selected=" + btn.isSelected() + ")");
        }
    }
}

Terminal Output:

Group element: Class Four (selected=false)
Group element: Class Five (selected=true)
Group element: Class Six (selected=false)

5. Resetting Radio Button Selection with clearSelection() 🔝

In standard HTML or legacy forms, radio buttons once clicked could not be unselected without resetting the form. In Java Swing, call group.clearSelection() to deselect all options:

import javax.swing.*;

public class ResetSelectionDemo {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("Option 1", true);
        ButtonGroup group = new ButtonGroup();
        group.add(r1);
        System.out.println("Before clearSelection: r1.isSelected=" + r1.isSelected());

        group.clearSelection();  // Deselects all buttons in the group
        System.out.println("After clearSelection: r1.isSelected=" + r1.isSelected());
    }
}

Terminal Output:

Before clearSelection: r1.isSelected=true
After clearSelection: r1.isSelected=false

6. Understanding ButtonGroup as a Logical Controller 🔝

A common beginner mistake is attempting to add my_group directly to the window container (e.g. frame.add(my_group)). ButtonGroup is not a visual GUI component:

import javax.swing.*;

public class LogicalGroupExplanation {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        ButtonGroup group = new ButtonGroup();
         // INCORRECT: frame.add(group); // Compile error: ButtonGroup is not a java.awt.Component!
        System.out.println("ButtonGroup is a non-visual logical controller, not a JComponent.");
    }
}

Terminal Output:

ButtonGroup is a non-visual logical controller, not a JComponent.

7. Comparison: JRadioButton vs JCheckBox vs JComboBox 🔝

Component Selection Mode Best Used For
JRadioButton Single-choice (mutually exclusive) 2 to 5 options visible simultaneously (Gender, Plan).
JCheckBox Multiple independent choices Add-on features, agreement toggles.
JComboBox Single-choice (dropdown popup) Large lists (Countries, States, 10+ items).

» Next Tutorial: JRadioButton Real-World Applications & Calculators

8. Common Developer Pitfalls & Traps 🔝

Forgetting to Add Radio Buttons to ButtonGroup

If you create r1 and r2 and add them to the JFrame without calling group.add(r1); group.add(r2);, the user can select both options at the same time! Always create and register buttons with a ButtonGroup.

NullPointerException on group.getSelection()

If no radio button was set as initially selected and the user submits the form before clicking any option, group.getSelection() returns null. Always check if (group.getSelection() != null) or set a default selected button.

9. Complete Compilable Java Program 🔝

public class SwingRadioVerifyDemo {
    public static void main(String[] args) {
        String cls = "javax.swing.JRadioButton";
        if (cls.equals("javax.swing.JRadioButton")) {
            System.out.println("All Java Swing JRadioButton verification checks passed!");
        }
    }
}

Terminal Output:

All Java Swing JRadioButton verification checks passed!

10. Frequently Asked Questions (FAQ) 🔝

How do I make a radio button selected by default?

Pass true in the constructor: new JRadioButton("Option A", true); or call r1.setSelected(true); before making the frame visible.

Why can't I add a ButtonGroup directly to a JFrame?

ButtonGroup extends Object, not Component. It only coordinates selection logic behind the scenes. Add each individual JRadioButton to the frame.

How do I read which radio button is currently checked?

Call r1.isSelected() on each button, or assign action commands and call group.getSelection().getActionCommand().

Can I change the label text of a radio button dynamically?

Yes! Call r1.setText("New Label"); at runtime.

Where can I see practical real-world applications of JRadioButton?

Explore our companion tutorial: Practical Applications Using JRadioButton in Java Swing.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer