Writing an Event Producer

An event producer is also known as the "source" of the event. Java does not define a base class or an interface for the event producer. However, the Listener design pattern requires that the event source provide at least these two methods for adding and removing listeners for the event that it produces:

The angle brackets (<>) represent that the "Event" should be replaced by the actual name of the event. In other words, the name of the methods depends on the event being produced. This naming convention is not enforced by Java's classes. However, not adhering to the convention will make the user classes unsuitable for use in Java components as the Java Beans model assumes these conventions. Here is a simple example of an event producer:

The event is constructed on Line 14. A reference to "this" is passed as the "event source" parameter and a unique integer is passed as the "id." In Lines 15-17, the code goes through all the listeners in the list and calls the method myEventOccured() on each listener. The event object is passed as the parameter, which constitutes the "firing" of the event.