devxlogo

Writing an Event Producer

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:

 public void add Listener (Listener e)public void removeListener(Listener e)

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:

 1. public class MyEventProducer {2.     private int id_ = 0;3.     Vector MyEventListener myEventListeners_ = new Vector();4. 5.     public void addMyEventListener (MyEventListener listener) {6.       listeners_.add(listener);7.     }8. 9.     public void removeMyEventListener(MyEventListener listener) {10.       listeners_.remove(listener);11.  }12. 13.  public void notifyMyEventOccured() {14.    MyEvent myEvent = new myEvent(this, i++);15.    while myEventListeners_.hasMoreElements() {16.      MyEventListener listener = myEventListeners_.nextElement();17.      listener.myEventOccured(myEvent);18.    }19. }

The MyEventProducer class defines three methods. The first two are used to add and remove listeners to and from a Vector of MyEventListener objects. The MyEventListener class is described in the Tip “Implementing the Event Listener Interface.” The third method creates and fires the event. The MyEvent object is described in the Tip “Using the EventObject Class.”

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist