I have a swing application that includes radio buttons on a form. I have the ButtonGroup
, however, looking at the available methods, I can't seem to get the name of the selected JRadioButton
. Here's what I can tell so far:
From ButtonGroup, I can perform a getSelection()
to return the ButtonModel
. From there, I can perform a getActionCommand
, but that doesn't seem to always work. I tried different tests and got unpredictable results.
Also from ButtonGroup
, I can get an Enumeration from getElements()
. However, then I would have to loop through each button just to check and see if it is the one selected.
Is there an easier way to find out which button has been selected? I'm programing this in Java 1.3.1 and Swing.
Button groups ( javax. swing. ButtonGroup ) are used in combination with radio buttons to ensure that only one radio button in a group of radio buttons is selected.
Methods Used :ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.
public JRadioButton(String text, boolean selected) Creates a radio button with the specified text and selection state. Parameters: text - the string displayed on the radio button selected - if true, the button is initially selected; otherwise, the button is initially unselected.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With