How To Create Your Own Events In Java

I’m pretty new to the Java language.  A couple of years ago I started looking into it then pursued PHP as my main focus, so I never really bit into the Java scene.  I now am able to focus on learning Java and I am learning a lot.

So here is something I have learned:

Creating custom objects with their own custom events.

When I learned how to do this (thanks to this helpful article: http://www.javaworld.com/javaworld/javaqa/2002-03/01-qa-0315-happyevent.html ), I was very excited.  I must have looked like a complete idiot when I shouted for joy in the office and then had to explain my trimuph to all who would hear.  My poor wife even got to listen to the story.  I’ve spared my children.

I’ll give a brief overview of what I learned from that article.  It is from 2002, but I found it very helpful, so check it out if you can.

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.

So that’s it in a nutshell; not too bad.  I think I may create a more usable and complete example.

Advertisements

37 thoughts on “How To Create Your Own Events In Java

  1. Hey, i just have to create the interface to deal with my specific event, my event class and i have to advise in one class where the event is going to fire right?

    1. Basically the class that is going to publish the event (broadcast it) to the listeners (subscribers) maintains a list of these listeners; these listeners implement a specific interface or abstraction that the publisher knows about; and whenever the publisher wants to notify these subscribers, it does so by iterating through them; for instance if my publisher is a GUI form and I have a logic that runs when the button is pushed, then the class that has the logic will subscribe to that particular button push event. Hope that helps.

      1. This should be part of the main article. It really put the peices together in human terms and made sense of the code. Being new to java from the .Net world and having to hit the ground running at a sr dev level there are a great many things i know can be done but have to find the correct way to do. This being a notable example.

        That said this article is by far the best example / tutorial ive seen on the topic.

  2. I think there’s a mistake in the name in the line 13:
    MyEventClass event = new EventClass(this);

    Should be
    MyEventClass event = new MyEventClass(this);

  3. Great article.. why dont u write the list as follows:

    private List _listeners = new ArrayList();

    that way u leverages java generics, right? or not? sorry im newbie in java too 😉

  4. I think your sample line of
    (MyEventClassListener) i.next().handleMyEventClassEvent(event);

    should be
    ((MyEventClassListener) i.next()).handleMyEventClassEvent(event);

    Which is to cast to the interface, then the event method is exposed.

  5. a very nice explanation to very vast concept……………….!!!!!!!!!!

    keep it up the good work dear.>!!!!!!!!
    10/10

  6. Thank you, I am new to this event listeners but by using this article i understood it well, Can you give me some explanation about how to handle events.

  7. A little off topic, but when creating a list, define the type to be kept within it to avoid possible type safety issues during execution; e.g., within MyEventSource {
    private List _listeners = new ArrayList ();

    This will also remove a couple compile warnings.

  8. Within your event handler, why do you pass in the general Event class rather than the purpose-built MyEventClass?
    (you may have a purpose here – just don’t know what it is)

    All that said, thanks for the post; it really helped me solve a problem changing my publish-subscribe mechanism to events from observer/observable.

  9. I personally would replace (in MyEventSource::fireEvent())

    Iterator i = _listeners.iterator();
    while(i.hasNext()) {
    ((MyEventClassListener) i.next()).handleMyEventClassEvent(event);
    }

    with

    for (MyEventClassListener listener : _listeners){
    listener.handleMyEventClassEvent(event);
    }

  10. Thank you for making this code available. It really explaines something complicated (at least I thought is was) in a down to earth way. Excellent.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s