简体   繁体   中英

Event Listeners in Java

I've been working with event listeners in AS3, but seems like there is none in java (except for graphics components). It's surprising.

The question is, how could i implement my own event listener in java? Maybe someone did that work before?

You can define a 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 practice you would probably 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"));
    }
}

您可以将PropertyChangeSupportPropertyChangeListener一起使用,也可以使用Observer模式。

First of all you need some source of events, so you can attache listener to it. If you need custom listener then you need also implement the custom source.

In Java you can find existing sources and listener interfaces. As you mentioned GUI is usually based on events. If you are into 3D then rendering engines deliver appropriate API (eg. collision detection ), file system hooks, properties change listeners ( Android ).

It depends what are your needs. For most usages there should be already a library that delivers you appropriate API.

While implementing your own solution then for application wide event handling the Event Bus might be a good choice. My preferred implementation is in Guava library: http://code.google.com/p/guava-libraries/wiki/EventBusExplained

您可以在Java中为要观察的对象扩展Observable类实现一种侦听器,并在侦听器上实现Observer

You don't need frameworks or Observer class. It's all built into the Java Beans spec since version 1.0 in 1995. It was supposed to be Java's answer to VB properties.

Here's a tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM