user225269
user225269

Reputation: 10893

Which radio button is selected in a button group

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()) {
    //...
}

Upvotes: 1

Views: 26745

Answers (5)

TimothyWynia
TimothyWynia

Reputation: 1

For dealing with a button group bg, you can get the buttons by calling the button group's getElements() method, and using that as the parameter for the Collections.list() method, just save the result in an arraylist. From there it is relatively simple to retrieve the correct button.

ArrayList<AbstractButton> arl = Collections.list(bg.getElements());
for (AbstractButton ab : arl) {
    JRadioButton jrb = (JRadioButton) ab;
    if (jrb.isSelected()) {
        return jrb;
    }
}

Upvotes: 0

sriram_koushik
sriram_koushik

Reputation: 31

I know the question was posted long back. Anyway, we can use the setActioncommand function. while creating the radio button, setActionCommand could be invoked to set the action command value, which could be used to refer to the radio button that was selected.

jRadioButton1.setActionCommand("jRadioButton1"); jRadioButton2.setActionCommand("jRadioButton2") . . String button_name = ((JToggleButton.ToggleButtonModel)button_group.getSelection()).getActionCommand();

Upvotes: 2

camickr
camickr

Reputation: 324207

Darryl's Select Button Group has a getSelectedButton() method.

Upvotes: 2

eee
eee

Reputation: 1053

ButtonGroup class does not provide a method to identify the currently selected button (inherited from AbstractButton) in the group if that is your intention. It only has clearSelection() method to clear the selected state of all buttons in the group (with exception for JButton and JMenuItem which don't have select/deselect button state).

One solution I can think of is to use a special variable or field (AbstractButton, JRadioButton or JRadioButtonMenuItem if it is in a menu item) to identify which one is currently selected by updating it inside each AbstractButton's action listener method (make sure to validate user clicks since it can be triggered more than once!). Use the variable (by typecasting it - for AbstractButton only) in other method(s).

Other than that, nope...you will need to do conditional branching.

Upvotes: 0

I82Much
I82Much

Reputation: 27336

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.

Upvotes: 3

Related Questions