Event listeners in Java

I've been using the event listener in AS3, but it doesn't seem to be in Java (except graphical components) Amazing

The question is, how do I implement my own event listener in Java? Maybe someone has done such a job before?

Solution

You can define the listener interface:

public interface EventListener {
    void fireEvent (Event e);
}

Then in your code:

EventListener lst = new EventListener() {
    @Override
    public void fireEvent (Event e) {
        //do what you want with e
    }
}

someObject.setListener(lst);
someObject.somethingHappened();

Then in someobject (in fact, you may hold a list of listeners):

public class SomeObject {
    private EventListener lst;

    public void setListener (EventListener lst) {
        this.lst = lst;
    }

    public void somethingHappened () {
        lst.fireEvent(new Event("Something Happened"));
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>