Creating a Custom Event

A new custom event must extends EventObject. Moreover, an event listener interface must be declared to allow objects to receive the new custom event. All listeners must extend from EventListener.

This example demonstrates all the steps necessary to create a new custom event.

// Declare the event. It must extend EventObject.
public class MyEvent extends EventObject {
    public MyEvent(Object source) {
        super(source);
    }
}

// Declare the listener class. It must extend EventListener.
// A class must implement this interface to get MyEvents.
public interface MyEventListener extends EventListener {
    public void myEventOccurred(MyEvent evt);
}

// Add the event registration and notification code to a class.
public class MyClass {
    // Create the listener list
    protected javax.swing.event.EventListenerList listenerList =
        new javax.swing.event.EventListenerList();

    // This methods allows classes to register for MyEvents
    public void addMyEventListener(MyEventListener listener) {
        listenerList.add(MyEventListener.class, listener);
    }

    // This methods allows classes to unregister for MyEvents
    public void removeMyEventListener(MyEventListener listener) {
        listenerList.remove(MyEventListener.class, listener);
    }

    // This private class is used to fire MyEvents
    void fireMyEvent(MyEvent evt) {
        Object[] listeners = listenerList.getListenerList();
        // Each listener occupies two elements - the first is the listener class
        // and the second is the listener instance
        for (int i=0; i<listeners.length; i+=2) {
            if (listeners[i]==MyEventListener.class) {
                ((MyEventListener)listeners[i+1]).myEventOccurred(evt);
            }
        }
    }
}
Here's an example of how to register for MyEvents.
MyClass c = new MyClass();

// Register for MyEvents from c
c.addMyEventListener(new MyEventListener() {
    public void myEventOccurred(MyEvent evt) {
        // MyEvent was fired
    }
});

Comments

21 Jan 2010 - 3:42pm by Anonymous (not verified)

Thanks.

28 Jun 2010 - 6:56pm by pascal (not verified)

Also the iteration can be written simpler:

foreach(MyEventListener listener : listenerList.getListenerList(MyEventListener.class)
listener.myEventOccurred(evt);

20 Aug 2010 - 2:45am by Stefano Gallina (not verified)

Hi,

it's a nice solution; but in which way can I fire the event ?
Cheers.

Stefano

12 Nov 2010 - 4:17am by Roger Kekhlekar (not verified)

Hi,

I'm trying to create a listener in J2ME for ByteArrayOutputStream.

Can you please provide some guidelines or an example.

Regards,
Roger Kekhlekar

18 Dec 2010 - 6:21am by Anonymous (not verified)

Thanks! Really helpfull

18 Dec 2010 - 6:43am by Anonymous (not verified)

Does anyone know why in for loop of the fireMyEvent method, the int i is increased by 2 instead of 1? (i+=2) thanks

20 Dec 2010 - 5:58pm by Anonymous (not verified)

It was in the comments,

// Each listener occupies two elements - the first is the listener class
// and the second is the listener instance

That's also why java has you add the class object, then the class instance; it needs both the way Java does "event" handling.

Unfortunately, if you were looking for "event" handlers as being the easy way to implement a hook/callback model in Java, you still need to look elsewhere. Because you need a listener object (note: not class, prepared object) in order to raise a signal event at all, there's no point in polling a state until it comes up and handling it.

To put this another way, the "listener" isn't really "listening" the way a guard on watch is listening. It's "listening" the way someone asleep next to a telephone is "listening".

To accomplish the first would require reflection, although it would have the advantage of treating the event listener interface as, you know, an interface.

21 Dec 2010 - 12:25am by Anonymous (not verified)

Just thought a little more about this; there is kind of a way to set up events so that it's more "something happened" and then things react to it, rather then "something happened" and then calling everyone who cares. And this answers the "how do you fire this" question from earlier.

You could have a "trigger" class, which holds the EventListenerList, which acts like a wrapper for another class, and then creates and populates EventObjects and dispatches them.

Basically something like the above, except separate MyClass from any event management (so MyClass just does whatever MyClass does, and everything else reacts to it). The MyClass object and the MyEvent are then created by the Trigger class.

The advantage is now the end user has a behavior which is a little closer to "every time I (or another function) call(s) a function, an event happens and a bunch of stuff reacts to the event", which at least as far as I'm concerned is the desired behavior.

So, like,

class Trigger

public static void void callAMyClassFunction()
{
MyClass source = new MyClass();
MyEvent evt = new MyEvent(source);
source.doSomething();
for (int i=0; i

11 Jan 2011 - 11:54pm by Prashant (not verified)

1000s of thanks

22 Feb 2011 - 1:00am by Gucci evening bag (not verified)

Third, the order process here is very easy here, you should only pay few minutes to complete ordering.

13 Mar 2011 - 3:19pm by Nemanja Simović (not verified)

Great stuff! The best example for making events in java. It's simple and code comments are explainable enough.

13 Apr 2011 - 6:32am by Anonymous (not verified)

Great and Simple EXAMPLE! Thanks!

13 Oct 2011 - 10:44am by You are Awesome (not verified)

Thanks a lot! this is Awesome

26 Oct 2011 - 5:55am by Michael Johnson (not verified)

Magnificent!! Frankly your writings are so interesting and I love to read the whole articles, and really appreciate for sharing helpful and interesting information.

29 Nov 2011 - 8:03pm by Anonymous (not verified)

I get errors when I add or remove something to the listenerList on the terms .add and .remove?

26 Dec 2011 - 2:49pm by Nemanja Simovic (not verified)

This is the simplest explanation that I found on internet. Thanks a lot!

4 Jan 2012 - 2:28am by Dale (not verified)

Thanks a lot! I looked a long time to find this and I now have it successfully installed and working beautifully.

16 Jan 2012 - 8:32am by Victor (not verified)

Thank you! Nice and neat example and truly helpful as well.

31 Jan 2012 - 8:49pm by Cholo (not verified)

Nice post.Thank you for taking the time to publish this information very useful! I've been looking for books of this nature for a way too long. I'm just glad that I found yours. Looking forward for your next post. Thanks :)

Cholo
www.0y7.net

6 Apr 2012 - 5:26pm by Sandaran (not verified)

Hey, you're the goto exrpet. Thanks for hanging out here.

8 Apr 2012 - 8:22pm by Akiko (not verified)

Thank You Steven,Glad U're enjoying the show. And one of the eisgbgt thrills of producing / director BSAP Dr. Who, is having Mark Kalita play The Doctor. Quite possibly the finest Voice Actor I've ever known. and The Doctor is the character he was literally born to play. Then factor in Paul's amazing scripts, and all the fabulous folks I've gotten to work with, and it's very much a dream gig for me.

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.