Sending Change Events in Swing

Swing uses two different change event classes. The first is the standard java.beans.PropertyChangeEvent class. This class passes a reference to the object, sending the change notification as well as the property name, its old value, and its new value. The second, javax. swing.event.ChangeEvent, is a lighter version that passes only a reference to the sending object—in other words, the name of the property that changed, as well as the old and new values, are omitted.

Because the ChangeEvent includes only a reference to the event originator, which never changes, you can always define a single ChangeEvent and reuse it over and over when firing events from your component.

The ChangeEvent Class

The ChangeEvent is a stripped-down version of the java.beans.PropertyChangeEvent class. This class has no methods or properties, only a constructor. This simplicity makes it a popular class for developers wanting to fire off their own events. Recipients get a reference to the source of the event but then must query the source directly to find out what just happened. It’s great for quick notifications or instances in which the state of the source component is so complex it’s hard to predict which pieces of information the recipient will need, but it shouldn’t be used simply to save the component author a little time at the expense of runtime inefficiency if the recipient always needs to look up information that could have been part of a PropertyChangeEvent.


public ChangeEvent(Object source)
The constructor for the ChangeEvent class. It takes only a single object, which represents the entity sending the event.

The ChangeListener Interface

Objects that intend to receive change events must implement the interface. They can then register to receive ChangeEvent objects from a publisher class. The ChangeListener interface consists of only one method.


public abstract void stateChanged(ChangeEvent e)
Implemented in a listener object to receive ChangeEvent notifications.


You may also like...