To add JRadioButtons to a ButtonGroup in Java, you need to follow these steps:
- 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();
- 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");
- 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.