Creating custom events in Java
First, create the event that your application will fire
Next, create the interface that has to be implemented by the classes that will receive your event MyEvent.
Then, create a controlComponent that knows what classes that are subscribing to your event MyEvent.
Now, this is the framework and it is possible to start creating subscribers and notifiers of MyEvent. Each notifier has to extend the MyControlComponent. To fire a new MyEvent, just
The subscriber's of MyEvent, has to register itself with the MyEventControlComponent, this is done by
Then implement the method(s) from the MyEventListener interface, and handle the events:
First, create the event that your application will fire
public MyEvent extends EventObject {
public static final MYEVENT_OPEN = 1;
public static final MYEVENT_CLOSE = 2;
private int type;
public MyEvent(int eventType) {
super(type);
type = eventType;
}
public int getType() {
return type;
}
}
Next, create the interface that has to be implemented by the classes that will receive your event MyEvent.
public interface MyEventListener extends java.util.EventListener {
public void myEventWasReceived(MyEvent event);
}
Then, create a controlComponent that knows what classes that are subscribing to your event MyEvent.
public abstract class MyEventControlComponent {
static EventListenerList myEventListeners = new EventListenerList();
public static addMyEventListener(MyEventListener listener) {
myEventListeners.add(MyEventListener.class, listener);
}
public static removeMyEventListener(MyEventListener listener) {
myEventListerers.remove(MyEventListener.class, listener);
}
protected void fireMyEvent(MyEvent event) {
Object[] lsteners = myEventListeners.getListenerList();
for (int i = 0; i<listeners.length; i+=2) {
if(listeners[i]==MyEventListener.class) ((MyEventListener)listeners[i+1]).myEventWasReceived(event);
}
}
}
Now, this is the framework and it is possible to start creating subscribers and notifiers of MyEvent. Each notifier has to extend the MyControlComponent. To fire a new MyEvent, just
this.fireMyEvent(new MyEvent(MyEvent.MY_EVENT_OPEN));
The subscriber's of MyEvent, has to register itself with the MyEventControlComponent, this is done by
public class MyTest implements MyEventListener {
public MyTest() {
MyEventControlComponent.addMyEventListener(this);
}
Then implement the method(s) from the MyEventListener interface, and handle the events:
public void myEventWasReceived(MyEvent event) {
//Some action based on the event, and its information
}
0 Comments:
Post a Comment
<< Home