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

3

17

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.

Overrate answered 21/7, 2013 at 9:38 Comment(1)
Show us what you tried. And read docs.oracle.com/javase/tutorial/uiswing/components/…Indoiranian
P
30

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();
    }
}
Posology answered 21/7, 2013 at 11:54 Comment(0)
H
6

Here's a radio button grouping:

JRadioButton button1 = ...;
button1.setSelected(true);
JRadioButton button2 = ...;
ButtonGroup group = new ButtonGroup();
group.add(button1);
group.add(button2);
Hilbert answered 21/7, 2013 at 9:43 Comment(2)
I tried this thing. But its showing a NUllPOinterException while a run.Overrate
@user2079152 the exception stack trace tells you exactly where the exception happens. If you can't understand it, the post your code and the full stack trace of the exception, in your question.Indoiranian
B
5
    JPanel radioButtonPanel = new JPanel();
    append = new JRadioButton("append");
    build = new JRadioButton("x.x.1");
    build.setSelected(true); //sets this button as selected on startup
    small = new JRadioButton("x.1.x");
    huge = new JRadioButton("1.x.x");

    // Create the button group to keep only one selected.
    ButtonGroup btnGroup = new ButtonGroup();
    btnGroup.add(append);
    btnGroup.add(build);
    btnGroup.add(small);
    btnGroup.add(huge);

Then you add your Buttons to your JPanel or something similar.

Bor answered 21/7, 2013 at 9:43 Comment(2)
Do we need to create a JPanel or can we simply add JRadioButtons to the JFrame directly?Overrate
Both should be possible, but it's preferred to use: JFrame with 1 or more JPanels. Each JPanel has 1 or more other Components like RadioButtons, Buttons, TextFields etc.Bor

© 2022 - 2024 — McMap. All rights reserved.