By Tony Bevis on Wednesday, 25 October 2023
Category: Java

Java programming course: 20.3 JavaBeans

JavaBeans

A JavaBean is a reusable component that is written to conform to certain conventions. Although they don't have to be, JavaBeans are often graphical in nature and in fact all the Swing graphical components are JavaBeans. This enables them to be used within builder tools such as NetBeans.

The essential conventions that mean that a class can be considered a JavaBean are:

[1] For boolean properties.

Here is a class called Address which you can create in the Utilities project. To keep things simple, it only has two properties, street and city:

Although not essential, it is useful for a JavaBean to fire a property change event whenever a property value has changed (i.e., each time one of the setter methods is called). The PropertyChangeSupport class (which is in the java.beans package) provides a convenient way to do this:

The argument passed when instantiating the PropertyChangeSupport object is the object which is the source of the changes, which in this case is this object.

In each setter method the old value is saved just before updating it, and finally the firePropertyChange() method is called to notify all listeners that a change to a property has occurred.

There are three passed arguments;


Note the two new methods to add and remove PropertyChangeListener objects, which just forward to the same methods within the PropertyChangeSupport object.

Client objects interested in being notified about property changes can implement the PropertyChangeListener interface and provide code for its propertyChange() method. Within that, you can call the PropertyChangeEvent object's getPropertyName(), getOldValue() and getNewValue() and process them as required.

Next lesson: 20.4 Networking 

Related Posts

Leave Comments