How do I get which JRadioButton is selected from a ButtonGroup
You must add setActionCommand
to the JRadioButton
then just do:
String entree = entreeGroup.getSelection().getActionCommand();
Example:
java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " +
buttonGroup.getSelection().getActionCommand());
I would just loop through your JRadioButtons
and call isSelected()
. If you really want to go from the ButtonGroup
you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?
I got similar problem and solved with this:
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
public class GroupButtonUtils {
public String getSelectedButtonText(ButtonGroup buttonGroup) {
for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
}
It returns the text of the selected button.