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