Java Reference
In-Depth Information
Listening to JRadioButton Events with an ItemListener
Depending on what you're trying to do, using an
ItemListener
with a
JRadioButton
is usually
not the desired event-listening approach. When an
ItemListener
is registered, a new
JRadioButton
selection notifies the listener twice: once for deselecting the old value and once for selecting
the new value. For reselections (selecting the same choice again), the listener is notified only once.
To demonstrate, the following listener will detect reselections, as the
ActionListener
did
earlier, and will report the selected (or deselected) element.
ItemListener itemListener = new ItemListener() {
String lastSelected;
public void itemStateChanged(ItemEvent itemEvent) {
AbstractButton aButton = (AbstractButton)itemEvent.getSource();
int state = itemEvent.getStateChange();
String label = aButton.getText();
String msgStart;
if (state == ItemEvent.SELECTED) {
if (label.equals(lastSelected)) {
msgStart = "Reselected -> ";
} else {
msgStart = "Selected -> ";
}
lastSelected = label;
} else {
msgStart = "Deselected -> ";
}
System.out.println(msgStart + label);
}
};
To work properly, some new methods will be needed for
RadioButtonUtils
to enable you
to attach the
ItemListener
to each
JRadioButton
in the
ButtonGroup
. They're listed in the
following section with the source for the complete example.
Listening to JRadioButton Events with a ChangeListener
The
ChangeListener
responds to the
JRadioButton
just as it does with the
JToggleButton
and
JCheckBox
. A subscribed listener is notified when the selected radio button is armed, pressed,
selected, or released and for various other properties of the button model. The only difference
with
JRadioButton
is that the
ChangeListener
is also notified of the state changes of the radio
button being deselected. The
ChangeListener
from the earlier examples could be attached to
the
JRadioButton
as well. It will just be notified more frequently.
The sample program shown in Listing 5-7 demonstrates all the listeners registered to the
events of two different
JRadioButton
objects. In addition, a
JButton
reports on the selected
elements of one of the radio buttons. Figure 5-12 shows the main window of the program.