conmadoi conmadoi - 1 year ago 109
Java Question

Create a custom event in Java

I want to do something like this in Java but I don't know the way:

When event "object 1 say 'hello'" happens,
then object 2 responds to that event by saying "hello".

Can somebody give me a hint or sample code?

Answer Source

You probably want to look into the observer pattern.

Here's some sample code to get you started:

import java.util.*;

// 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...");


class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();


        initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."

Related article: Java: Creating a custom event

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download