Java Reference
In-Depth Information
the primary three properties with the appropriate getter and setter methods:
get
/
setText()
,
get
/
setIcon()
, and
is
/
setSelected()
, or
setAction(action)
. The other properties have corre-
sponding getter and setter methods.
The more visual configurable options of
JToggleButton
(and its subclasses) include the
various icons for the different states of the button. Besides the standard icon, you can display
a different icon when the button is selected, among other state changes. However, if you're
changing icons based on the currently selected state, then
JToggleButton
probably isn't the
most appropriate component to use. You should use one of its subclasses,
JCheckBox
or
JRadioButton
, explored later in this chapter.
■
Note
Keep in mind that the
JButton
component ignores the
selectedIcon
property.
Handling JToggleButton Selection Events
After configuring a
JToggleButton
, you can handle selection events in one of three ways: with
an
ActionListener
, an
ItemListener
, or a
ChangeListener
. This is in addition to providing an
Action
to the constructor, which would be notified like an
ActionListener
.
Listening to JToggleButton Events with an ActionListener
If you're interested only in what happens when a user selects or deselects the
JToggleButton
,
you can attach an
ActionListener
to the component. After the user selects the button, the
component notifies any registered
ActionListener
objects. Unfortunately, this isn't the desired
behavior, because you must then actively determine the state of the button so that you can
respond appropriately for selecting or deselecting. To find out the selected state, you must get
the model for the event source, and then ask for its selection state, as the following sample
ActionListener
source shows:
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton)actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Action - selected=" + selected + "\ n");
}
};
Listening to JToggleButton Events with an ItemListener
The better listener to attach to a
JToggleButton
is the
ItemListener
. The
ItemEvent
passed to
the
itemStateChanged()
method of
ItemListener
includes the current selection state of the
button. This allows you to respond appropriately, without needing to search for the current
button state.
To demonstrate, the following
ItemListener
reports the state of a selected
ItemEvent
-
generating component: