質問

Although, every AbstractButton can be added to the ButtonGroup (according to the Java API), i wanted to ask, which elements really make sense to get added.

The following two definitely do:

  • JRadioButton
  • JRadioButtonMenuItem

I wanted to know about:

  • JCheckBox <- which, like JRadioButton, inherits from JToggleButton
  • Any other AbstractButton
役に立ちましたか?

解決

ButtonGroup is used to create a multiple-exclusion scope for a set of buttons. Creating a set of buttons with the same ButtonGroup object means that turning "on" one of those buttons turns off all other buttons in the group.

A ButtonGroup can be used with any set of objects that inherit from AbstractButton. Typically a ButtonGroup contains instances of JRadioButton, JRadioButtonMenuItem, or JToggleButton. It wouldn't make sense to put an instance of JButton or JMenuItem in a ButtonGroup because JButton and JMenuItem don't implement the selected state.

Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group. There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible JRadioButton to the group and then programmatically select that button to turn off all the displayed JRadioButtons. For example, a normal button with the label "none" could be wired to select the invisible JRadioButton.

For examples and further information on using ButtonGroups see How to Use JRadioButtons, a section in The Java Tutorial.

他のヒント

In addition to the answer above - there is a way, to create ButtonGroup that will allow to clear selection in group (the state when none of the group buttons will be selected) without any additional code - just extend ButtonGroup and override setSelected method like this:

public void setSelected ( ButtonModel model, boolean selected )
{
    if ( selected || !unselectable )
    {
        super.setSelected ( model, selected );
    }
    else
    {
        clearSelection ();
    }
}

That will allow buttons to become unselected.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top