Java Reference
In-Depth Information
// Define ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
button.setBackground(new Color(red, green, blue));
}
};
// Define PropertyChangeListener
PropertyChangeListener propertyChangeListener =
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
String property = propertyChangeEvent.getPropertyName();
if ("background".equals(property)) {
button2.setBackground((Color)propertyChangeEvent.getNewValue());
}
}
};
// Attach listeners
button1.addActionListener(actionListener);
button1.addPropertyChangeListener(propertyChangeListener);
button2.addActionListener(actionListener);
frame.add(button1, BorderLayout.NORTH);
frame.add(button2, BorderLayout.SOUTH);
frame.setSize(300, 100);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Although this example causes only a color change from button selection, imagine if the
background color of the first button could be changed from a couple of hundred different places
other than the one action listener! Without a property change listener, each of those places
would be required to also change the background color of the second button. With the property
change listener, it's only necessary to modify the background color of the primary object—the
first button, in this case. The change would then automatically propagate to the other components.
The Swing library also uses the ChangeEvent / ChangeListener pair to signify state changes.
Although similar to the PropertyChangeEvent / PropertyChangeListener pair, the ChangeEvent
doesn't carry with it the new and old data value settings. You can think of it as a lighter-weight
version of a property change listener. The ChangeEvent is useful when more than one property
value changes, because ChangeEvent doesn't need to package the changes.
Search WWH ::




Custom Search