To create custom Java events we need basicly three classes:
- The event class which will be fired
- An interface which indicating responsibility of event listeners of this event
- The class which fires the Java events
When these classes are prepared, other classes can subscribe to events by providing their event listener.
An event class must extend java.util.EventObject class. Below you can see an event class example which I used in an application that exchanges messages over TCP/IP sockets.
package prototype.communication.events;
import java.util.EventObject;
/**
*
* @author Server
*/
public class CommunicationEvent extends EventObject {
private int eventType;
public static final int ConnectionLost = 0;
public static final int MessageReceived = 1;
public static final int ConnectionEstablished = 2;
public static final int ServerSocketFailed = 3;
public CommunicationEvent(Object source, int eventType) {
super(source);
this.eventType = eventType;
}
public int getEventType() {
return eventType;
}
}
Coding the interface is usually trivial, note that this interface must extend java.util.EventListener interface which is a tagging interface.
package prototype.communication.events;
import java.util.EventListener;
/**
*
* @author Server
*/
public interface CommunicationEventListener extends EventListener{
public void communicationEventReceived(CommunicationEvent event);
}
The third class which will fire should provide following functions to enable other class to subscribe to events:
public synchronized void addEventListener(CommunicationEventListener l);
public synchronized void removeEventListener(CommunicationEventListener l);
Following field can be used to store event listeners:
private List eventListeners;
Then implementation of add and remove functions follows intuitively:
public synchronized void addEventListener(CommunicationEventListener l) {
eventListeners.add(l);
}
public synchronized void removeEventListener(CommunicationEventListener l) {
eventListeners.remove(l);
}
Whenever this class needs to fire an event it will iterate over listeners and will call communicationEventReceived method of EventListener interface. You can see an example function that fires an event:
private synchronized void fireCommunicationEvent(int eventType) {
CommunicationEvent event = new CommunicationEvent(this, eventType);
Iterator listeners = eventListeners.iterator();
while (listeners.hasNext()) {
listeners.next().communicationEventReceived(event);
}
}
