简体   繁体   中英

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

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.

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();

Darryl的“ 选择按钮组”具有getSelectedButton()方法。

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM