Wednesday, March 14, 2012

How to create custom objects with their own custom events in Java?


Four things you need:
  1. An Event Class
  2. An Interface
  3. An event source
  4. An event listener
The event class will extend java.util.EventObject like this:
public class MyEventClass extends java.util.EventObject {
             //here's the constructor
             public MyEventClass(Object source) {
                 super(source);
             }
}
The interface will look something like this:
public interface MyEventClassListener {
         public void handleMyEventClassEvent(EventObject e);
}
The event source will look something like this:
public class MyEventSource {
  private List _listeners = new ArrayList();
  public synchronized void addEventListener(MyEventClassListener listener)      {
    _listeners.add(listener);
  }
  public synchronized void removeEventListener(MyEventClassListener listener)   {
    _listeners.remove(listener);
  }

  // call this method whenever you want to notify
  //the event listeners of the particular event
  private synchronized void fireEvent() {
    MyEventClass event = new MyEventClass(this);
    Iterator i = _listeners.iterator();
    while(i.hasNext())  {
      (MyEventClassListener) i.next().handleMyEventClassEvent(event);
    }
  }
}
The event listener will look something like this:
public class MyEventListener implements MyEventClassListener {
  // ... code here

  //implement the required method(s) of the interface
  public void handleMyEventClassEvent(EventObject e)    {
    // handle the event any way you see fit
  }
}
You’ll need to register the MyEventListener object with the MyEventSource object by call its addEventListener method.


No comments:

Post a Comment