Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
87 views
in JAVA by (112k points)
How to get the selected JRadioButton from a ButtonGroup?

Please log in or register to answer this question.

1 Answer

0 votes
by (112k points)

To get the selected JRadioButton from a ButtonGroup in Java, you can use the getSelection() method of the ButtonGroup class. 

Here's an example:

ButtonGroup buttonGroup = new ButtonGroup();

JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");

buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);

// ... Add the radio buttons to a container ...

// Get the selected radio button
JRadioButton selectedRadioButton = (JRadioButton) buttonGroup.getSelection();

if (selectedRadioButton != null) {
    // A radio button is selected
    System.out.println("Selected option: " + selectedRadioButton.getText());
} else {
    // No radio button is selected
    System.out.println("No option selected");
}
 

In this example, a ButtonGroup is created and two JRadioButtons are added to it. The getSelection() method is called to get the selected radio button, which is returned as a ButtonModel. The ButtonModel is cast to a JRadioButton using (JRadioButton), and its getText() method is called to get the label of the selected button.

If no radio button is selected, getSelection() returns null.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked May 6, 2023 in JAVA by kvdevika (112k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...