Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Mar 17, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 <Event>Listener (<Event>Listener e)
public void remove<Event>Listener(<Event>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();
5.     public void addMyEventListener (MyEventListener listener) {
6.       listeners_.add(listener);
7.     }
9.     public void removeMyEventListener(MyEventListener listener) {
10.       listeners_.remove(listener);
11.  }
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.

Ajit Sagar
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date