Noel Enete
Custom Events

To create an event, first create an event object that will be passed from the source to the target object. Then build a target object with the ability to receive the event and a source object with the ability to trigger the event.

The event object contains enough information to describe the event.

The target object must supply a method to receive the event object. The source object must provide methods to trigger the event and methods to register the target to receive the event. Then code must be written to instantiate the source and target objects and wire them together.

Simple Event Class

This event represents a graduation. The only information that is stored to describe the event is the year of the graduation.

Figure 1: GraduationEvent

By convention, event names should take the form XxxEvent, where Xxx is the name of the event. In this case the event name is graduation so the class name is GraduationEvent.

Every event class should extend EventObject (which is in the java.util.* package). The constructor in the example above is required because EventObject's constructor requires the event source as a parameter. The call to super() passes the source to EventObject's constructor.

An instance of the class above is passed from the source to the destination object when the graduation event occurs.

Simple Target Class

The method by which the target class receives the event is defined in a listener interface.

Figure 2: GraduationListener

The target class provides the method to receive the event by implementing the listening interface.

Figure 3: TargetClass

Simple Source Class

The source object provides methods to trigger the event and methods to register the target for receiving events.

Figure 4: SourceClass

Wiring Source to Target

The target object is connected to the source object by implementing the listening interface and registering with the source object to be a listener.

Figure 5: MyEvent

by Noel Enete . . . . . .