How do I get which JRadioButton is selected from a ButtonGroup
Asked Answered
S

14

91

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.

Sepulveda answered 14/10, 2008 at 14:5 Comment(2)
Java 1.3.1? As in only supported on vintage Solaris 8, and no bugs from April?Ceramics
Yeah, I know. The desktop machines that I'm developing this for have older applications that still run on this version, and I don't want to mess with that.Sepulveda
S
47

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?

Singleminded answered 14/10, 2008 at 14:12 Comment(2)
please consider this reading : javaworld.com/article/2077509/core-java/…Reinsure
@Thufir : ButtonGroup tells Java that only on of the JRadioButtons of the group should be selected. without that, all of them could be selected simultaneously.Kitti
P
88

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.

Phenylalanine answered 5/11, 2012 at 13:8 Comment(2)
I think you should just post that method 'getSelectedButtonText' as the answer. Perfect answer ty!Assault
Nice solution, to get the text of a selected button - BUT one should be aware that the output changes when the button is renamed (e.g. when translated). Binding any functionality to the text displayed in the GUI is rather discouraged.Dressingdown
S
47

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?

Singleminded answered 14/10, 2008 at 14:12 Comment(2)
please consider this reading : javaworld.com/article/2077509/core-java/…Reinsure
@Thufir : ButtonGroup tells Java that only on of the JRadioButtons of the group should be selected. without that, all of them could be selected simultaneously.Kitti
S
41

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());
Slimsy answered 11/8, 2014 at 15:11 Comment(0)
C
5

I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.

If you really want the widget, then you can test each with isSelected, or maintain a Map<ButtonModel,JRadioButton>.

Ceramics answered 14/10, 2008 at 15:34 Comment(0)
S
5

You can put and actionCommand to each radio button (string).

this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");

Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:

String selection = this.state_group.getSelection().getActionCommand();

Hope this helps

Soyuz answered 14/6, 2016 at 3:27 Comment(0)
S
3

The following code displays which JRadiobutton is selected from Buttongroup on click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.

 JRadioButton firstRadioButton=new JRadioButton("Female",true);  
 JRadioButton secondRadioButton=new JRadioButton("Male");  

 //Create a radio button group using ButtonGroup  
 ButtonGroup btngroup=new ButtonGroup();  

 btngroup.add(firstRadioButton);  
 btngroup.add(secondRadioButton);  

 //Create a button with text ( What i select )  
 JButton button=new JButton("What i select");  

 //Add action listener to created button  
 button.addActionListener(this);  

 //Get selected JRadioButton from ButtonGroup  
  public void actionPerformed(ActionEvent event)  
  {  
     if(event.getSource()==button)  
     {  
        Enumeration<AbstractButton> allRadioButton=btngroup.getElements();  
        while(allRadioButton.hasMoreElements())  
        {  
           JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
           if(temp.isSelected())  
           {  
            JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
           }  
        }            
     }
  }
Supinator answered 20/1, 2013 at 17:43 Comment(1)
hmm ... this differs from earlier answers in that .. ?Erickericka
L
1
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class RadioButton extends JRadioButton {

    public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
        public Object[] getSelectedObjects() {
            if ( isSelected() ) {
                return new Object[] { RadioButton.this };
            } else {
                return new Object[0];
            }
        }

        public RadioButton getButton() { return RadioButton.this; }
    }

    public RadioButton() { super(); setModel(new RadioButtonModel()); }
    public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }

    public static void main(String[] args) {
        RadioButton b1 = new RadioButton("A");
        RadioButton b2 = new RadioButton("B");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        b2.setSelected(true);
        RadioButtonModel model = (RadioButtonModel)group.getSelection();
        System.out.println(model.getButton().getText());
    }
}
Locomotive answered 14/5, 2014 at 13:4 Comment(0)
C
1

Typically, some object associated with the selected radio button is required. It is not necessarily a String representing the button's label. It could be an Integer containing the button's index or an object of more complicated type T. You could fill and use a Map<ButtonModel, T> as Tom Hawtin suggested, but I propose to extend the model and place the objects there. Here's an improved ButtonGroup that uses this approach.

import javax.swing.*;

@SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
    @Override
    public void add(AbstractButton b) {
        throw new UnsupportedOperationException("No object supplied");
    }

    public void add(JRadioButton button, T attachedObject) {
        ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
        model.setSelected(button.isSelected());
        button.setModel(model);
        super.add(button);
    }

    @SuppressWarnings("unchecked")
    public T getSelectedObject() {
        ButtonModel selModel = getSelection();
        return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
    }

    public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
        public T obj;

        private ExtendedModel(T object) {
            obj = object;
        }
    }
}

You can use this utility class instead of ButtonGroup. Create an object of this class and add buttons along with associated objects to it. For example,

SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();

for (int i = 1; i <= 5; i++) {
    JRadioButton button = new JRadioButton("Button #" + i, i == 3); // select the 3rd button
    group.add(button, i);
    panel.add(button);
}

After this, you can get the object associated with the currently selected button anytime you need by simply calling getSelectedObject(), like this:

int selectedButtonIndex = group.getSelectedObject();

In case you need just the buttons themselves, you can use the next non-generic class instead.

import javax.swing.JRadioButton;

@SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
    public void add(JRadioButton button) {
        super.add(button, button);
    }

    @Override
    public void add(JRadioButton button, JRadioButton attachedObject) {
        throw new UnsupportedOperationException("Use the short form of addition instead");
    }

    public JRadioButton getSelectedButton() {
        return getSelectedObject();
    }
}
Campobello answered 1/4, 2020 at 11:58 Comment(0)
T
0

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

Tremann answered 14/10, 2008 at 14:20 Comment(1)
I tried, this but I was getting a NPE. I did a little research, and found this: java.sun.com/javase/6/docs/api/javax/swing/… Since JRadioButton's button model is JToggleButton.ToggleButtonModel, it will always return null.Sepulveda
M
0

Add the radiobuttons to a button group then:

buttonGroup.getSelection().getActionCommand

Masefield answered 28/11, 2013 at 11:39 Comment(1)
not answering the question (which was to get the selected JRadioButton vs. its actionCommand)Erickericka
W
0

Use the isSelected() method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.

Wrongheaded answered 11/8, 2014 at 14:8 Comment(0)
F
0
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; 
public class MyJRadioButton extends JFrame implements ActionListener
{
    JRadioButton rb1,rb2;  //components
    ButtonGroup bg;
    MyJRadioButton()
{
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    rb1=new JRadioButton("male");
    rb2=new JRadioButton("female");

    //add radio button to button group
    bg=new ButtonGroup();
    bg.add(rb1);
    bg.add(rb2);

    //add radio buttons to frame,not button group
    add(rb1);
    add(rb2);
    //add action listener to JRadioButton, not ButtonGroup
    rb1.addActionListener(this);
    rb2.addActionListener(this);
    pack();
    setVisible(true);
}
public static void main(String[] args)
{
    new MyJRadioButton(); //calling constructor
}
@Override
public void actionPerformed(ActionEvent e) 
{
    System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}

}

Frothy answered 24/3, 2015 at 19:15 Comment(1)
While this snippet can answer the question is better to explain how it solves OP problemTighten
A
0

Ale Rojas's answer works fine:

As alternative you can also use the My_JRadiobutton11.addActionListener(this); on your JButton and then make your actions in the actionPerformed function like this (It just uses an extra variable which you have to instantiate (e.g Private String selection;) but it's not a big deal):

public void actionPerformed(ActionEvent arg0) {
      if(arg0.getSource() == My_JRadiobutton11){
          //my selection
          selection = "Become a dolphin";
      }else if(arg0.getSource() == My_JRadiobutton12){
          //my selection
          selection = "Become a Unicorn";
      } ..etc 
 }
Amourpropre answered 14/5, 2021 at 16:9 Comment(0)
G
-3
jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();

... then for every button:

buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);

...listener

ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioButtonActionPerformed(evt);
            }
        };

...do whatever you need as response to event

protected void radioButtonActionPerformed(ActionEvent evt) {            
       System.out.println(evt.getActionCommand());
    }
Gisele answered 14/10, 2008 at 14:36 Comment(1)
That confuses input events and state changes. Other code may change the state. It also takes responsibility away from the button group model.Ceramics

© 2022 - 2024 — McMap. All rights reserved.