Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get which JRadioButton is selected from a ButtonGroup

Tags:

java

swing

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.

like image 911
Joel Avatar asked Oct 14 '08 14:10

Joel


People also ask

What is a button group which control is generally used with a ButtonGroup?

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.

Which method is used to enable the JRadioButton?

Methods Used :ButtonGroup() : Use to create a group, in which we can add JRadioButton. We can select only one JRadioButton in a ButtonGroup.

What is a JRadioButton?

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.


2 Answers

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.

like image 165
Rendicahya Avatar answered Oct 10 '22 09:10

Rendicahya


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?

like image 24
Draemon Avatar answered Oct 10 '22 07:10

Draemon