Java Reference
In-Depth Information
AbstractButton abstract3 =
new JCheckBox("Check Box");
panel.add(abstract3);
group.add(abstract3);
AbstractButton abstract4 =
new JRadioButtonMenuItem("Radio Button Menu Item");
panel.add(abstract4);
group.add(abstract4);
AbstractButton abstract5 =
new JCheckBoxMenuItem("Check Box Menu Item");
panel.add(abstract5);
group.add(abstract5);
frame.add(panel, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Figure 5-1.
ButtonGroup/ToggleButtonModel example
As previously stated, the
ButtonGroup
class represents a logical grouping of
AbstractButton
components. The
ButtonGroup
is not a visual component; therefore, there's nothing visual on
screen when a
ButtonGroup
is used. Any
AbstractButton
component can be added to the grouping
with
public void add(AbstractButton abstractButton)
. Although any
AbstractButton
component can belong to a
ButtonGroup
, only when the data model for the component is
ToggleButtonModel
will the grouping have any effect. The result of having a component with a
data model of
ToggleButtonModel
in a
ButtonGroup
is that after the component is selected, the
ButtonGroup
deselects any currently selected component in the group.
■
Note
Technically speaking, the model doesn't need to be
ToggleButtonModel
as long as the custom
model exhibits the same behavior of limiting the number of selected component models to one.