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
42 views
in JAVA by (117k points)
How to add JRadioButtons to a ButtonGroup?

Please log in or register to answer this question.

1 Answer

0 votes
by (117k points)

To add JRadioButtons to a ButtonGroup in Java, you need to follow these steps:

  1. Create a new instance of ButtonGroup class using the default constructor or a constructor that takes a string parameter representing the name of the group.
ButtonGroup group = new ButtonGroup();
 
  1. Create instances of JRadioButton class, which represent the options you want to group together. You can create as many JRadioButtons as you need, and set their labels and other properties as desired.
JRadioButton option1 = new JRadioButton("Option 1");
JRadioButton option2 = new JRadioButton("Option 2");
 
  1. Add each JRadioButton to the ButtonGroup instance using the add() method. This method ensures that only one radio button in the group can be selected at a time.
group.add(option1);
group.add(option2);
 

Here's an example that shows how to add JRadioButtons to a ButtonGroup:

import javax.swing.*;

public class RadioButtonExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));

        ButtonGroup group = new ButtonGroup();

        JRadioButton option1 = new JRadioButton("Option 1");
        JRadioButton option2 = new JRadioButton("Option 2");

        group.add(option1);
        group.add(option2);

        JPanel panel = new JPanel();
        panel.add(option1);
        panel.add(option2);

        frame.add(panel);
        frame.setVisible(true);
    }
}
 

In this example, we created two JRadioButtons named "Option 1" and "Option 2", and added them to a ButtonGroup named "group". Then, we added the JRadioButtons to a JPanel, which was added to the JFrame. When the user selects one of the radio buttons, only one of the buttons in the group will be selected at a time.

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 (117k 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

...