TestEventSource.java Source code

Java tutorial

Introduction

Here is the source code for TestEventSource.java

Source

import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;

abstract class TestEventSource {
    public abstract void addListener(TestEventListener l);

    public abstract void removeListener(TestEventListener l);

    public abstract void fireEvent(java.util.EventObject o);

    public void test() {
        addListener(new TestEventListener("A"));
        fireEvent(new java.util.EventObject(this));
    }
}

class TestEventListener implements EventListener {
    String id;

    public TestEventListener(String id) {
        this.id = id;
    }

    public void handleEvent(EventObject o) {
        System.out.println(id + " called");
        if (id.equals("C")) {
            ((TestEventSource) o.getSource()).removeListener(this);
        }
    }
}

public class Main extends TestEventSource {
    ArrayList listeners = new ArrayList();

    public void addListener(TestEventListener l) {
        listeners.add(l);
    }

    public void removeListener(TestEventListener l) {
        listeners.remove(l);
    }

    public void fireEvent(EventObject o) {
        for (int i = 0; i < listeners.size(); i++) {
            TestEventListener l = (TestEventListener) listeners.get(i);
            l.handleEvent(o);
        }
    }

    public static void main(String[] args) {
        Main pfles = new Main();
        pfles.test();
    }

}