Java Reference
In-Depth Information
Icon checkBoxIcon = new CheckBoxIcon();
JCheckBox aCheckBox3 = new JCheckBox("Anchovies", checkBoxIcon);
JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust", checked);
frame.setLayout(new GridLayout(0,1));
frame.add(aCheckBox1);
frame.add(aCheckBox2);
frame.add(aCheckBox3);
frame.add(aCheckBox4);
frame.setSize(300, 200);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Handling JCheckBox Selection Events
As with the
JToggleButton
, you can handle
JCheckBox
events in any one of three ways: with an
ActionListener
, an
ItemListener
, or a
ChangeListener
. The constructor that accepts an
Action
just adds the parameter as an
ActionListener
.
Listening to JCheckBox Events with an ActionListener
Subscribing to
ActionEvent
generation with an
ActionListener
allows you to find out when the
user toggles the state of the
JCheckBox
. As with
JToggleButton
, the subscribed listener is told of
the selection, but not the new state. To find out the selected state, you must get the model for the
event source and ask, as the following sample
ActionListener
source shows. This listener
modifies the check box label to reflect the selection state.
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton)actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
String newLabel = (selected ? SELECTED_LABEL : DESELECTED_LABEL);
abstractButton.setText(newLabel);
}
};
Listening to JCheckBox Events with an ItemListener
For
JCheckBox
, as with
JToggleButton
, the better listener to subscribe to is an
ItemListener
. The
ItemEvent
passed to the
itemStateChanged()
method of
ItemListener
includes the current
state of the check box. This allows you to respond appropriately, without need to find out the
current button state.
To demonstrate, the following
ItemListener
swaps the foreground and background colors
based on the state of a selected component. In this
ItemListener
, the foreground and back-
ground colors are swapped only when the state is selected.