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.
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.
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.
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.
Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected.
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();
}
}
Here's a radio button grouping:
JRadioButton button1 = ...;
button1.setSelected(true);
JRadioButton button2 = ...;
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With