Java Reference
In-Depth Information
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
AbstractButton abstractButton = (AbstractButton)itemEvent.getSource();
Color foreground = abstractButton.getForeground();
Color background = abstractButton.getBackground();
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
abstractButton.setForeground(background);
abstractButton.setBackground(foreground);
}
}
};
Listening to JCheckBox Events with a ChangeListener
The
ChangeListener
responds to the
JCheckBox
just as with the
JToggleButton
. A subscribed
ChangeListener
would be notified when the button is armed, pressed, selected, or released.
In addition, the
ChangeListener
is also notified of changes to the
ButtonModel
, such as for the
keyboard mnemonic (
KeyEvent.VK_S
) of the check box. Because there are no
ChangeListener
differences to demonstrate between a
JToggleButton
and a
JCheckBox
, you could just attach the
same listener from
JToggleButton
to the
JCheckBox
, and you'll get the same selection responses.
The sample program in Listing 5-4 demonstrates all the listeners subscribed to the events
of a single
JCheckBox
. To demonstrate that the
ChangeListener
is notified of changes to other
button model properties, a keyboard mnemonic is associated with the component. Given that
the
ChangeListener
is registered before the
mnemonic
property is changed, the
ChangeListener
is notified of the property change. Because the foreground and background colors and text
label aren't button model properties, the
ChangeListener
isn't told of these changes made by
the other listeners.
■
Note
If you did want to listen for changes to the foreground or background color properties, you would
need to attach a
PropertyChangeListener
to the
JCheckBox
.
Listing 5-4.
Listening for JCheckBox Selection
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SelectingCheckBox {
private static String DESELECTED_LABEL = "Deselected";
private static String SELECTED_LABEL = "Selected";