How to get value of selected radioButton of buttonGroup

Malwinder Singh picture Malwinder Singh · Sep 13, 2014 · Viewed 56.1k times · Source

How to get value of selected radioButton? I tried using buttonGroup1.getSelection().getActionCommand() (as posted in some of answers here) but it is not working. Also, i am temporarily using this code but i want to know is this a good practice or not?

//Consider that maleRButton and femaleRButton are two radioButtons of 
//same buttonGroup
String getGender()
{
    if(maleRButton.isSelected())
    {
        return "Male";
    }
    else if(femaleRButton.isSelected())
    {
        return "Female";
    }
    else
    {
        return null;
    }
}

Answer

camickr picture camickr · Sep 13, 2014

I tried using buttonGroup1.getSelection().getActionCommand()

That approach will work, but for some reason it looks like you manually need to set the action command when you create the button. For example:

JRadioButton maleButton = new JRadioButton( "Male" );
maleButton.setActionCommand( maleButton.getText() );

This acutally seems like a bit of a bug to me since usually the action command defaults to the text if the action command is not set.