Java Reference
In-Depth Information
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
if (state == ItemEvent.SELECTED) {
System.out.println("Selected");
} else {
System.out.println("Deselected");
}
}
};
Listening to JToggleButton Events with a ChangeListener
Attaching a ChangeListener to a JToggleButton provides even more flexibility. Any attached
listener will be notified of the data model changes for the button, corresponding to changes in
its armed , pressed , and selected properties. Listening for notification from the three listeners—
ActionListener , ItemListener , and ChangeListener —allows you to react seven different times.
Figure 5-3 shows the sequencing of the ButtonModel property changes, and when the model
notifies each of the listeners.
Figure 5-3. JToggleButton notification sequencing diagram
To demonstrate the ChangeListener notifications, the following code fragment defines a
ChangeListener that reports the state changes to the three properties of the button model:
ChangeListener changeListener = new ChangeListener() {
public void stateChanged(ChangeEvent changeEvent) {
AbstractButton abstractButton = (AbstractButton)changeEvent.getSource();
ButtonModel buttonModel = abstractButton.getModel();
boolean armed = buttonModel.isArmed();
boolean pressed = buttonModel.isPressed();
boolean selected = buttonModel.isSelected();
System.out.println("Changed: " + armed + "/" + pressed + "/" + selected);
}
};
Search WWH ::




Custom Search