What is a java.util.EventListener?

Viewed 13023

I can't find the answer to this question. What is a java.util.EventListener? How does it work? I have already done some research on google but I only found this, which isn't very clear: a tagging interface that all event listener interfaces must extend.

Can someone please help?

2 Answers

A listener is a class containing methods that are invoked when certain actions happen.

java.util.EventListener is a marker interface(an interface without any methods) that all listeners should implement.

In fact, it does not even add any functionality but it may be helpful with some IDEs and code-analysis tools.

So, if you want to create your own custom event (that you trigger), you need to somehow call all your listener methods when the event occurs.

For example, you can do this like the following:

At first, you create an interface for your listeners that extends EventListener:

public interface MyListener extends EventListener{
    void onEvent();
}

Then, you will need to create a mechanism to register and call all the events:

private Collection<MyListener> listeners=new HashSet<>();
public void register(MyListener listener){
    listeners.add(listener);
}
public void eventHappens(){
    for(MyListener listener:listeners){
        listener.onEvent();
    }
}

Then, you can creator a Listener using

public class MyListenerImpl implements MyListener{
    private String msg;
    public MyListenerImpl(String data){
        this.data=data;
    }
    @Override
    public void onEvent(){
        System.out.println(msg);
    }
}

and you can register it using

register(new MyListenerImpl("Event occurs"));

Whenever a eventHappens() is called(you can call it if you e.g. receive a network packet), all your registered listeners will be executed.

For example:

register(new MyListenerImpl("listener 1 called"));
register(new MyListenerImpl("listener 2 called"));
System.out.println("calling event");
eventHappens();

would print

calling event

listener 1 called

listener 2 called

The first Google hit is the EventListener documentation, as you seem to have discovered.

See that blue navigation bar at the very top of the page? The fourth word is a “Use” link. Go to that.

EventListener provides typesafe polymorphism. For example, java.awt.Component has a getListeners method which requires a subclass of EventListener.

EventListener is actually part of the Java Beans specification. From section 6.4 of that specification:

Since the new Java event model is based on method invocation we need a way of defining and grouping event handling methods. We require that event handling methods be defined in EventListener interfaces that inherit from java.util.EventListener. By convention these EventListener interfaces are given names ending in “Listener”.

A class that wants to handle any of the set of events defined in a given EventListener interface should implement that interface.

Related