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.