Java Program using JRadioButton with ActionListener


In this program, You will learn how to implement JRadioButton with ActionListener in Java.


JRadioButton r1,r2;

public void actionPerformed(ActionEvent e) { }


Example: How to implement JRadioButton with ActionListener in Java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;

class Test extends JFrame implements ActionListener {

    JButton b1, b2;
    JRadioButton r1, r2;

    Test() {

        r1 = new JRadioButton("Male");
        r1.setBounds(30, 20, 90, 40);
        add(r1);

        r2 = new JRadioButton("Female");
        r2.setBounds(130, 20, 90, 40);
        add(r2);

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

        b1 = new JButton("Check");
        b1.setBounds(30, 130, 60, 40);
        add(b1);
        b1.addActionListener(this);

        b2 = new JButton("Exit");
        b2.setBounds(120, 130, 60, 40);
        add(b2);
        b2.addActionListener(this);

        setLayout(null);
        setSize(400, 400);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent ev) {
        if (ev.getSource().equals(b1)) {
            if (r1.isSelected()) {
                JOptionPane.showMessageDialog(this, "Male is Selected");
            }

            if (r2.isSelected()) {
                JOptionPane.showMessageDialog(this, "Female is Selected");
            }
        }

        if (ev.getSource().equals(b2)) {
            System.exit(0);
        }

    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

Java JRadioButton