How to add a radio button group in a core java program such that only one radio button is selected at one time?

shubh picture shubh · Jul 21, 2013 · Viewed 88.4k times · Source

I am building a project in core java. BUt i'm stuck in making a radio button group ( for entering the gender (male/female). For that i need a radio group such that only one radio button is selected at one time; and take the input into the database accordingly. Please help.

Answer

G.Srinivas Kishan picture G.Srinivas Kishan · Jul 21, 2013

Kindly try using ButtonGroup component and add two JRadioButton components named male and female to the ButtonGroup object and then display it in a JFrame using setVisible(true); method.

The Below code should be useful :-

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;

public class Rb extends JFrame {
    Rb() {
        JRadioButton male = new JRadioButton("male");
        JRadioButton female = new JRadioButton("Female");
        ButtonGroup bG = new ButtonGroup();
        bG.add(male);
        bG.add(female);
        this.setSize(100, 200);
        this.setLayout(new FlowLayout());
        this.add(male);
        this.add(female);
        male.setSelected(true);
        this.setVisible(true);
    }

    public static void main(String args[]) {
        Rb j = new Rb();
    }
}