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

谢谢。

最佳答案

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

// 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);
    }
  }
}

客户端代码通常使用匿名内部类来注册处理程序:
Button b = new Button();
b.addClickListener(new ClickListener() {
  public void clicked(ClickEvent e) {
    // handle event
  }
});

10-04 10:59