Java Documentation

JRadioButton: Single-choice Options

JRadioButton is used when the user must choose exactly one option from a small set, such as gender or category. A ButtonGroup ensures that only one button is selected at a time.

Example: Gender selection using JRadioButton

This example creates three radio buttons (Male, Female, Others) and groups them using ButtonGroup so that only one can be selected at a time.

JRadioButtonDemo.java
import javax.swing.*;
import java.awt.*;

class MyFrame extends JFrame {
    MyFrame() {
        setTitle("Components - JRadioButton");

        JRadioButton b1 = new JRadioButton("Male");
        JRadioButton b2 = new JRadioButton("Female");
        JRadioButton b3 = new JRadioButton("Others");

        ButtonGroup bg = new ButtonGroup();

        bg.add(b1);
        bg.add(b2);
        bg.add(b3);

        JLabel gender = new JLabel("Select Your Gender: ");

        add(gender);

        add(b1);
        add(b2);
        add(b3);

        setLayout(new FlowLayout());
        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class JRadioButtonDemo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
Reference & full codeView on GitHub

What is JRadioButton?

A JRadioButton represents one choice in a set of mutually exclusive options. When placed in a ButtonGroup, selecting one radio button automatically deselects the others.

  • Used for Yes/No, Male/Female, and similar single-choice inputs.
  • Must be grouped with ButtonGroup for mutual exclusion.
  • Still uses layouts (like FlowLayout) to control placement.

Line-by-line: Understanding the JRadioButton example

We reuse the same JFrame pattern. Here we highlight how radio buttons are created, grouped, and added to the interface.

JRadioButton b1 = new JRadioButton("Male");
JRadioButton b2 = new JRadioButton("Female");
JRadioButton b3 = new JRadioButton("Others");

Creates three radio button components, each with a different label.

ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);

Puts all radio buttons into the same group so that selecting one automatically deselects the others. This enforces single-choice behavior.

JLabel gender = new JLabel("Select Your Gender: ");
add(gender);

Adds a label that explains what the radio buttons represent.

add(b1);
add(b2);
add(b3);

Adds the grouped radio buttons to the frame so the user can see and select them. FlowLayout arranges them in a row.

Radio buttons in real forms

Radio buttons are standard for surveys and forms where you must choose one option. Later, we will read which button is selected and react to the user's choice.