Currently I'm getting the selected button in this way, but I don't if this is the right/best method. MAybe there something more easy or object oriented than this.
private int getFilterType(JRadioButton... buttons) {
for (int i = 0, n = buttons.length; i < n; i++) {
if (buttons[i].isSelected()) {
return i + 1;
}
}
return buttons.length + 1;
}
I like using the ButtonGroup itself for this. i.e.,
If you have to know which button was pushed, I'd say it's best to give it an individual listener. No worries then.
I don't know if there is a way to get rid of the for loop. But at least you can use the
ButtonGroup
to dump the var-args. See an example here.You can use Darryl's Select Button Group which extend ButtonGroup to give you easy access to the radio button.
What you can do is to use a
ButtonGroup
(doc here) to which you add all theJRadioButton
. The group will take care of managing the mutual exclusion of the button as well as providing you thegetSelection()
method which returns the underlying model of the radio button pressed. Then you can find an easy way to distinguish between the various models (maybe you can retrieve the parent of the model or use thesetActionCommand
andgetActionCommand
like in:and then you can easily understand which one it is..
Use ButtonGroup. The good thing about using the button group is that it takes care of things such as togglig between radio buttons for you, so that you don't have to worry about it.
You add your buttons to the group like so:
and when you need to get the selected button, you just use
You can also add listeners to each button, as shown in this example.