Java Reference
In-Depth Information
Although the
add()
method is typically the only
ButtonGroup
method you'll ever need, the
following class definition shows that it's not the only method of
ButtonGroup
in existence:
public class ButtonGroup implements Serializable {
// Constructor
public ButtonGroup();
// Properties
public int getButtonCount();
public Enumeration getElements();
public ButtonModel getSelection();
// Other methods
public void add(AbstractButton aButton);
public boolean isSelected(ButtonModel theModel) ;
public void remove(AbstractButton aButton);
public void setSelected(ButtonModel theModel, boolean newValue);
}
One interesting thing the class definition shows is that given a
ButtonGroup
, you cannot
directly find out the selected
AbstractButton
. You can directly ask only which
ButtonModel
is
selected. However,
getElements()
returns an
Enumeration
of all the
AbstractButton
elements in
the group. You can then loop through all the buttons to find the selected one (or ones) by using
code similar to the following:
Enumeration elements = group.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = (AbstractButton)elements.nextElement();
if (button.isSelected()) {
System.out.println("The winner is: " + button.getText());
break; // Don't break if sharing models -- could show multiple buttons selected
}
}
The other interesting method of
ButtonGroup
is
setSelected()
. The two arguments of the
method are a
ButtonModel
and a
boolean
. If the
boolean
value is
false
, the selection request is
ignored. If the
ButtonModel
isn't the model for a button in the
ButtonGroup
, then the
ButtonGroup
deselects the currently selected model, causing no buttons in the group to be selected. The
proper usage of the method is to call the method with a model of a component in the group and
a new state of
true
. For example, if
aButton
is an
AbstractButton
and
aGroup
is the
ButtonGroup
,
then the method call would look like
aGroup.setSelected(aButton.getModel(), true)
.
■
Note
If you add a selected button to a
ButtonGroup
that already has a previously selected button, the
previous button retains its state and the newly added button loses its selection.
Now, let's look at the various components whose data model is the
ToggleButtonModel
.