Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 566
shubh Avatar asked Jul 21 '13 09:07

shubh


People also ask

How do I make sure only one radio button is selected in Java?

We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We use “ButtonGroup” class to create a ButtonGroup and add radio button in a group. Methods Used : JRadioButton() : Creates a unselected RadioButton with no text.

How do you group radio buttons together?

You group radio buttons by drawing them inside a container such as a Panel control, a GroupBox control, or a form. All radio buttons that are added directly to a form become one group. To add separate groups, you must place them inside panels or group boxes.

What object is used to ensure that only one radio button in a given group is selected at a time?

The ToggleGroup object provides references to all radio buttons that are associated with it and manages them so that only one of the radio buttons can be selected at a time.

How many radio buttons in a frame can be selected at the same time?

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected.


2 Answers

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();
    }
}
like image 65
G.Srinivas Kishan Avatar answered Sep 20 '22 19:09

G.Srinivas Kishan


Here's a radio button grouping:

JRadioButton button1 = ...;
button1.setSelected(true);
JRadioButton button2 = ...;
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
like image 43
tbodt Avatar answered Sep 20 '22 19:09

tbodt