Java Reference
In-Depth Information
After you attach the ChangeListener to a JToggleButton and select the component by
pressing and releasing the mouse over the component, the following output results:
Changed: true/false/false
Changed: true/true/false
Changed: true/true/true
Changed: true/false/true
Changed: false/false/true
With all three listeners attached to the same button, notification of registered ItemListener
objects would happen after the selected property changes—in other words, between lines 3
and 4. Listing 5-2 demonstrates all three listeners attached to the same JToggleButton . With
regard to the registered ActionListener objects, notification happens after releasing the button,
but before the armed state changes to false , falling between lines 4 and 5.
Listing 5-2. Listening for Toggle Selection
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SelectingToggle {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Selecting Toggle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToggleButton toggleButton = new JToggleButton("Toggle Button");
// Define ActionListener
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");
}
};
// Define ChangeListener
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