Java Reference
In-Depth Information
By registering PropertyChangeListener objects with the various components that support
this type of listener, you can reduce the amount of source code you must generate after the
initial listening setup. For instance, the background color of a Swing component is bound,
meaning someone can register a PropertyChangeListener to a component to be notified when
the background setting changes. When the value of the background property for that component
changes, anyone listening is notified, allowing an Observer to change its background color to
the new setting. Therefore, if you want all the components of your program to have the same
background color, you can register them all with one component. Then, when that single
component changes its background color, all the other components will be notified of the
change and will modify their backgrounds to the new setting.
Note Although you can use a PropertyChangeListener to “share” a common property setting among
components, you can also map the property of a subject to a different property of the Observer.
The program in Listing 2-3 demonstrates using a PropertyChangeListener . It creates two
buttons. When either button is selected, the background of the selected button is changed to
some random color. The second button is listening for property changes within the first button.
When the background color changes for the first button, the background color of the second
button is changed to that new value. The first button isn't listening for property changes for the
second button. Therefore, when the second button is selected, changing its background color,
this change doesn't propagate back to the first button.
Listing 2-3. Property Change Listener Sample
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.Random;
public class BoundSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Button Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton button1 = new JButton("Select Me");
final JButton button2 = new JButton("No Select Me");
final Random random = new Random();
 
Search WWH ::




Custom Search