Malwinder Malwinder - 1 year ago 79
Java Question

How to get value of selected radioButton of buttonGroup

How to get value of selected

I tried using
(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()
return "Male";
else if(femaleRButton.isSelected())
return "Female";
return null;

Answer Source

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.