Which radio button is selected in a button group

user225269 picture user225269 · Mar 10, 2011 · Viewed 26.5k times · Source

What can I do to get which radiobutton is selected on a buttongroup without doing this:

if (jRadioButton1.isSelected()) {
    //...
}

if (jRadioButton2.isSelected()) {
    //...
}

if (jRadioButton3.isSelected()) {
    //...
}

if (jRadioButton4.isSelected()) {
    //...
}

Answer

I82Much picture I82Much · Mar 10, 2011

You can get the ButtonModel for the selected button via the getSelection() method of ButtonGroup. I don't know how you can avoid conditionally branching on the selected button though, unless you have some sort of ancillary data structure mapping from ButtonModel to actions to perform, for instance. If you had that, then you could just fire the action based on the returned ButtonModel.