Java: Creating a custom event

Here's an example of how create your own events and listen to them. It's called the observer pattern. In this example the initiator prints "Hello" and the HelloListener responds with "Hello there!".

// An interface to be implemented by everyone
// interested in "Hello" events
interface HelloListener {
    void someoneSaidHello();
// Someone who says "Hello"
class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

    public void addListener(HelloListener toAdd) {

    public void sayHello() {
        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
// Someone interested in "Hello" events
class Responder implements HelloListener {
    public void someoneSaidHello() {
        System.out.println("Hello there!");

And here's a little example runner:

class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();
        initiater.sayHello();  // "Hello!" and "Hello there!"

Comments (2)

User avatar

Than you for this example. It works perfectly!

by MrJW |  Reply
User avatar

Good! Simple and clear!

by wibrst |  Reply

Add comment