Which JRadioButton is selected

I have several JRadioButtons in a ButtonGroup.

   private ButtonGroup radioGroup= new ButtonGroup();
   private JRadioButton radio1= new JRadioButton("Red");
   private JRadioButton radio2= new JRadioButton("Green");
   private JRadioButton radio3= new JRadioButton("Blue");

   radioGroup.add(radio1);
   radioGroup.add(radio2);
   radioGroup.add(radio3);

      

How can I check which one has been selected?

With System.out.println(radioGroup.getSelection())

I only get something like javax.swing.JToggleButton$ToggleButtonModel@32b3714

.

+3


source to share


4 answers


From the selected ButtonModel you can get the actionCommand String (if you didn't forget to set it!).

// code not compiled, run, nor tested in any way
ButtonModel model = radioGroup.getSelection();
String actionCommand = (model == null) ? "" : model.getActionCommand():
System.out.println(actionCommand);

      



But this will only work if you set the actionCommand first .. For example,

// code not compiled, run, nor tested in any way
String[] colors = {"Red", "Green", "Blue"};
JRadioButton[] radioBtns = new JRadioButton[colors.length];
for (int i = 0; i < radioBtns.length; i++) {
   radioBtns[i] = new JRadioButton(colors[i]);
   radioBtns[i].setActionCommand(colors[i]);
   radioGroup.add(radioBtns[i]);
   somePanel.add(radioBtns[i]);
}

      

+6


source


What you see is the toString

default implementation of the method . And ButtonGroup#getSelection

will return the ButtonModel

selected one JRadioButton

.



See also How to get which JRadioButton is selected from the ButtonGroup .

+3


source


If listeners are connected, an easy way to identify the source is to invoke ActionEvent.getSource()

.

+3


source


This will return the text of the selected radiobutt from the buttongroup

    Enumeration<AbstractButton> allRadioButton=radioGroup.getElements();  
    while(allRadioButton.hasMoreElements())  
    {  
       JRadioButton temp=(JRadioButton)allRadioButton.nextElement();  
       if(temp.isSelected())  
       {  
          JOptionPane.showMessageDialog(null,"You select : "+temp.getText());  
       }  
    }            

      

0


source







All Articles