简体   繁体   English

Java中的事件监听器

[英]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). 我一直在使用AS3中的事件监听器,但似乎在java中没有(除了图形组件)。 It's surprising. 这令人惊讶。

The question is, how could i implement my own event listener in java? 问题是,我怎样才能在java中实现自己的事件监听器? Maybe someone did that work before? 也许有人之前做过这项工作?

You can define a Listener interface: 您可以定义一个Listener接口:

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): 然后在someObject中(实际上你可能会有一个监听器列表):

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. 在Java中,您可以找到现有的源和listener接口。 As you mentioned GUI is usually based on events. 正如您所提到的,GUI通常基于事件。 If you are into 3D then rendering engines deliver appropriate API (eg. collision detection ), file system hooks, properties change listeners ( Android ). 如果你是3D,那么渲染引擎提供适当的API(例如collision detection ),文件系统挂钩,属性改变监听器( Android )。

It depends what are your needs. 这取决于你的需求。 For most usages there should be already a library that delivers you appropriate API. 对于大多数用途,应该已经有一个库,可以为您提供适当的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 我首选的实现是在Guava库中: http//code.google.com/p/guava-libraries/wiki/EventBusExplained

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

You don't need frameworks or Observer class. 您不需要框架或Observer类。 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. 它自1995年版本1.0以来都内置于Java Beans规范中。它应该是Java对VB属性的回答。

Here's a tutorial: 这是一个教程:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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