-
To be a bound property, the bean must send a PropertyChange event when
the property changes.
-
Thus, the bean must support listeners. Listeners can register themselves
with the
addPropertyChangeListener(PropertyChangeListener listener)
and
removePropertyChangeListener(PropertyChangeListener listener)
methods.
-
The PropertyChangeListener interface has a single method, public
void propertyChange(PropertyChangeEvent evt). This method
is called when a bound property is changed.
-
But, there is a convenience method available to make your life easier.
Create an instance field of type PropertyChangeSupport,
and pass the constructor a reference to the this object (an instance
of the current object). Then you can proxy
your dirty work to it.
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
public void addPropertyChangeListener(PropertyChangeListener listener)
{
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener
listener) {
pcs.removePropertyChangeListener(listener);
}
Whenever an event happens, simply call this method of the
PropertyChangeSupport object:
firePropertyChange(String propertyName, Object oldValue, Object
newValue)
There are a few different signatures of this method in JDK 1.4.* (see
the online
API documentation for details). One takes ints for the
new and old values, another takes booleans, and a fourth takes an event
object itself. Like the ResultSet methods in the slide about indexed
properties, this allows the programmer to choose the optimal level of complexity.
-
This way you don't have to deal with the dirty work of managing listeners.
-
Remember that Swing components are beans. So if your bean extends
a Swing component, you can simply piggy back off of its event handling
structure.
-
Beans that want to be notified of chagnes to bound properties must implement
the PropertyChangeListener
interface.
-
Thus, they must implement the one and only method of this interface, void
propertyChange(PropertyChangeEvent event) .
-
This method is called whenever the value of the bound property is changed.
It is passed an Event object, which contains useful information about the
change.
-
public Object getOldValue() - gets the previous value of the property.
-
public Object getNewValue() - gets the new value of the property.
-
Example
-
If we change our database with setDatabase(), or change our username
and password, we may want to fire an event to any other beans that we're
using in our Database bean.
Packaging Beans in a Jar file