Practical Applications Using JRadioButton

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

public class RadioButtonApplicationsMasterDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JRadioButton Applications Master Demo");
            frame.setBounds(100, 100, 480, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().setLayout(null);

             // Solution 1: Enable / Disable Target Button
            JButton b1 = new JButton("Button b1");
            b1.setBounds(36, 30, 110, 25);
            frame.getContentPane().add(b1);

            JRadioButton r1 = new JRadioButton("Enable", true);
            r1.setBounds(36, 65, 80, 25);
            frame.getContentPane().add(r1);

            JRadioButton r2 = new JRadioButton("Disable");
            r2.setBounds(120, 65, 80, 25);
            frame.getContentPane().add(r2);

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

            r1.addActionListener(e -> b1.setEnabled(true));
            r2.addActionListener(e -> b1.setEnabled(false));

            frame.setVisible(true);

             // Verification simulation:
            r2.doClick();
            System.out.println("b1 isEnabled after Disable: " + b1.isEnabled());
            r1.doClick();
            System.out.println("b1 isEnabled after Enable: " + b1.isEnabled());
        });
    }
}

Output:

b1 isEnabled after Disable: false
b1 isEnabled after Enable: true
[GUI Window Rendered: 480x300, Solutions 1, 2, and 3 active]

1. Hands-On JRadioButton Practice Challenges 🔝

Build the following three GUI applications from our JRadioButton Tutorial:

  1. Challenge 1 (Enable / Disable Button): Add a button b1 and a radio button group with r1 ("Enable") and r2 ("Disable"). Selecting r1 enables b1, and selecting r2 disables b1.
  2. Challenge 2 (External Selection Trigger): Place radio buttons r1 and r2 in a group. Add two push buttons b1 ("Select r1") and b2 ("Select r2"). Clicking b1 programmatically selects r1, and clicking b2 selects r2.
  3. Challenge 3 (Dynamic Label Synchronization): Place a text field t1, button b1, and radio button r1. By default, t1 displays r1's label. Editing t1 and clicking b1 updates r1's label to match the text field.

2. Solution 1: Enabling and Disabling a Button via Radio Buttons 🔝

Radio button enable selectionRadio button disable selection

Attach an ActionListener to each radio button:

import javax.swing.*;

public class RadioButtonSolution1 {
    public static void main(String[] args) {
        JButton b1 = new JButton("Button b1");
        JRadioButton r1 = new JRadioButton("Enable", true);
        JRadioButton r2 = new JRadioButton("Disable");
        ButtonGroup group = new ButtonGroup();
        group.add(r1); group.add(r2);

        r1.addActionListener(e -> {
            b1.setEnabled(true);
            System.out.println("Button enabled!");
        });
        r2.addActionListener(e -> {
            b1.setEnabled(false);
            System.out.println("Button disabled!");
        });

        r2.doClick();
    }
}

Output:

Button disabled!

3. Solution 2: Programmatic Selection via Push Buttons 🔝

Selecting Radio buttons via push buttons

Invoke r1.setSelected(true); or r2.setSelected(true); in push button handlers:

import javax.swing.*;

public class RadioButtonSolution2 {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("r1", true);
        JRadioButton r2 = new JRadioButton("r2");
        ButtonGroup group = new ButtonGroup();
        group.add(r1); group.add(r2);

        JButton b2 = new JButton("Select r2");
        b2.addActionListener(e -> {
            r2.setSelected(true);  // Programmatically select r2
            System.out.println("Selection: r1=" + r1.isSelected() + ", r2=" + r2.isSelected());
        });

        b2.doClick();
    }
}

Output:

Selection: r1=false, r2=true

4. Solution 3: Synchronizing Radio Button Label with JTextField 🔝

Managing Label of JRadioButton

Read the initial label using r1.getText(). Update the radio label with r1.setText(t1.getText()):

import javax.swing.*;

public class RadioButtonSolution3 {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("Standard Plan");
        JTextField t1 = new JTextField(r1.getText());
        System.out.println("Initial textfield text: " + t1.getText());

        t1.setText("Premium Plan");
        r1.setText(t1.getText());  // Update radio label from text field
        System.out.println("Updated radiobutton label: " + r1.getText());
    }
}

Output:

Initial textfield text: Standard Plan
Updated radiobutton label: Premium Plan

5. Real-World Application: Dynamic Shipping Rate Calculator 🔝

Radio buttons drive checkout pricing:

import javax.swing.*;

public class ShippingRateCalculator {
    public static int calculateTotal(int basePrice, JRadioButton rExpress) {
        return rExpress.isSelected() ? basePrice + 15 : basePrice + 5;
    }
    public static void main(String[] args) {
        JRadioButton express = new JRadioButton("Express (+15 USD)", true);
        int total = calculateTotal(50, express);
        System.out.println("Computed Order Total: " + total + " USD");
    }
}

Output:

Computed Order Total: 65 USD

6. Clearing All Selections in a Form Reset 🔝

Call group.clearSelection();:

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);
        group.clearSelection();
        System.out.println("All cleared. Any selected? " + (group.getSelection() != null));
    }
}

Output:

All cleared. Any selected? false

7. Comparison: Radio Button Event Handling Approaches 🔝

Listener / Trigger When It Triggers Best Used For
ActionListener When user clicks radio button Immediate UI actions (enabling/disabling controls).
ItemListener When state transitions (select/deselect) Dual tracking (e.g. logging both old and new states).
External JButton When Submit button is clicked Form submission (reading r1.isSelected()).

» Next Tutorial: Transferring Data from One Window to Another

8. Common Developer Pitfalls & Traps 🔝

Initial State Desynchronization in Solution 1

If r2 ("Disable") is selected by default, call b1.setEnabled(false); at startup to keep state in sync.

Text Clipping When Changing Radio Labels Dynamically

Changing text to a longer string clips text if bounds width is too narrow. Always ensure sufficient width.

9. Complete Compilable Java Program 🔝

public class RadioApplicationsVerifyDemo {
    public static void main(String[] args) {
        boolean sol1 = true, sol2 = true, sol3 = true;
        if (sol1 && sol2 && sol3) {
            System.out.println("All Java Swing JRadioButton applications verification checks passed!");
        }
    }
}

Output:

All Java Swing JRadioButton applications verification checks passed!

10. Frequently Asked Questions (FAQ) 🔝

Does setSelected(true) trigger an ActionListener?

No. setSelected(true) updates state without firing an event. Call r1.doClick(); to fire events.

How do I pass the selected radio option to a second window?

Read r1.getText() and pass it to the child window. See Data Transfer Between Windows.

Can I store multiple independent radio groups on the same form?

Yes! Create separate ButtonGroup instances (e.g. ButtonGroup genderGroup = new ButtonGroup(); and ButtonGroup shippingGroup = new ButtonGroup();).

How do I save the chosen radio option into MySQL?

Read the selected text and include it in your SQL INSERT query (see JFrame to MySQL Insert).

Where should I go to display tabular data?

Check out our guide on Displaying Tabular Data with JTable.

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