Java 中的事件引发处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1204982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:52:53  来源:igfitidea点击:

Event raise-handling in Java

javaevents

提问by bdhar

How to raise custom events and handle in Java. Some links will be helpful.

如何在 Java 中引发自定义事件和处理。一些链接会有所帮助。

Thanks.

谢谢。

回答by kgiannakakis

Java hasn't built-in support for delegates and events like C#. You would need to implement the Observeror Publish/Subscribepattern yourself.

Java 没有像 C# 这样的对委托和事件的内置支持。您需要自己实现观察者发布/订阅模式。

回答by Rorick

Java has no in-language support for events handling. But there's some classes that can help. You may look at java.awt.Eventclass; java.awt.eventand java.beanspackages. First package is a base for event handling in AWT and Swing GUI libraries. java.beanspackage contains supporting stuff for Java Beans specification, including property change events and bean context events.

Java 没有对事件处理的语言支持。但是有一些课程可以提供帮助。你可以看看java.awt.Event类;java.awt.eventjava.beans包裹。第一个包是 AWT 和 Swing GUI 库中事件处理的基础。java.beans包包含Java Beans 规范的支持内容,包括属性更改事件和 bean 上下文事件。

Generally, event handling is implemented according to Observer or Publish/Subscribe patterns (as mentioned by kgiannakakis)

通常,事件处理是根据观察者或发布/订阅模式实现的(如kgiannakakis 所述

回答by Pavel Minaev

There are no first-class events in Java. All event handling is done using interfaces and listener pattern. For example:

Java 中没有一流的事件。所有事件处理都是使用接口和侦听器模式完成的。例如:

// Roughly analogous to .NET EventArgs
class ClickEvent extends EventObject {
  public ClickEvent(Object source) {
    super(source);
  }
}

// Roughly analogous to .NET delegate
interface ClickListener extends EventListener {
  void clicked(ClickEvent e);
} 

class Button {
  // Two methods and field roughly analogous to .NET event with explicit add and remove accessors
  // Listener list is typically reused between several events

  private EventListenerList listenerList = new EventListenerList();

  void addClickListener(ClickListener l) {
    clickListenerList.add(ClickListener.class, l)
  }

  void removeClickListener(ClickListener l) {
    clickListenerList.remove(ClickListener.class, l)
  }

  // Roughly analogous to .net OnEvent protected virtual method pattern -
  // call this method to raise the event
  protected void fireClicked(ClickEvent e) {
    ClickListener[] ls = listenerList.getListeners(ClickEvent.class);
    for (ClickListener l : ls) {
      l.clicked(e);
    }
  }
}

Client code typically uses anonymous inner classes to register handlers:

客户端代码通常使用匿名内部类来注册处理程序:

Button b = new Button();
b.addClickListener(new ClickListener() {
  public void clicked(ClickEvent e) {
    // handle event
  }
});

回答by Bob

Java lacks intrinsic event handling, but there are libraries to help you accomplish this. Check out javaEventing, http://code.google.com/p/javaeventing/It works much as in C# where you first define your events, and then register event listeners. You trigger events using EventManager.triggerEvent(..someEvent). It allows you to provide custom conditions and payloads with your events as well.

Java 缺乏内在的事件处理,但有一些库可以帮助您实现这一点。查看 javaEventing,http://code.google.com/p/javaeventing/它的工作原理与在 C# 中首先定义事件,然后注册事件侦听器非常相似。您可以使用 EventManager.triggerEvent(..someEvent) 触发事件。它还允许您为事件提供自定义条件和有效负载。

bob

鲍勃

回答by Gonen

If you're looking for a .net type delegate event, I propose this templated solution. It's advantage is that no hard casts are required, and a listener could implement several "events" as long as they are using different event classes.

如果您正在寻找 .net 类型委托事件,我建议使用此模板化解决方案。它的优点是不需要强制转换,只要它们使用不同的事件类,侦听器就可以实现多个“事件”。

import java.util.EventListener;
import java.util.EventObject;
// replaces the .net delegate

public interface GenericEventListener<EventArgsType extends EventObject>
    extends EventListener {
    public void eventFired(EventArgsType e);
}

//------------------------------------------------

import java.util.EventObject;
import java.util.Vector;
// replaces the .net Event keyword

public class GenericEventSource<EventArgsType extends EventObject> {
    private Vector<GenericEventListener<EventArgsType>> listenerList =
        new Vector<GenericEventListener<EventArgsType>>();

    //TODO handle multi-threading lock issues
    public void addListener(GenericEventListener<EventArgsType> listener) {
        listenerList.add(listener);
    }

    //TODO handle multi-threading lock issues
    public void raise(EventArgsType e) {
        for (GenericEventListener<EventArgsType> listener : listenerList) {
            listener.eventFired(e);
        }
    }
}

//------------------------------------------------

// like a .net class extending EventArgs
public class MyCustomEventArgs extends EventObject {
    private int arg;
    public MyCustomEventArgs(Object source, int arg) {
        super(source);
        this.arg = arg;
    }
    public int getArg() {
        return arg;
    }
}

//------------------------------------------------

// replaces the .net event handler function. Can be put in a nested class, Java style
// Listener can handle several event types if they have different EventArg classes
public class MyCustomListener implements GenericEventListener<MyCustomEventArgs> {
    private Object source = null;
    private int arg;
    public void eventFired(MyCustomEventArgs e) {
        source = e.getSource();
        arg = e.getArg();
        // continue handling event...
    }
}

//------------------------------------------------

import GenericEventListener;
import GenericEventSource;
// this is the class that would like to throw events (e.g. MyButton)
public class MyCustomEventSource {
    // This is like declaring a .net public Event field of a specific delegate type
    GenericEventSource<MyCustomEventArgs> myEvent = new GenericEventSource<MyCustomEventArgs>();

    public GenericEventSource<MyCustomEventArgs> getEvent() {
        return myEvent;
    }
}

//------------------------------------------------

// Examples of using the event
MyCustomListener myListener1 = new MyCustomListener();
MyCustomEventSource mySource = new MyCustomEventSource();
mySource.getEvent().addListener( myListener1 );
mySource.getEvent().raise( new MyCustomEventArgs(mySource,5));