是否可以编写自己的对象来提供ActionEvent?

我已经在线查看了java教程,他们似乎都关注捕获已经编写过的其他组件给出的ActionEvents。 是否有可能编写自己的对象,这些对象具有触发actionEvents的标准集,然后可以被已注册为侦听器的其他类捕获?

例如:如果我想要一个计算绵羊的对象发送一个actionEvent,当100只绵羊被计入所有已注册为听众的睡眠对象时。

有没有办法做到这一点有任何在线教程?

任何帮助是极大的赞赏。

是的,一旦有人向您展示如何创建自己的听众,这非常简单。

首先,您创建自己的EventObject。 这是我的一个项目的一个例子。

import gov.bop.rabid.datahandler.bean.InmateDataBean; import java.util.EventObject; public class InmatePhotoEventObject extends EventObject { private static final long serialVersionUID = 1L; protected InmateDataBean inmate; public InmatePhotoEventObject(Object source) { super(source); } public InmateDataBean getInmate() { return inmate; } public void setInmate(InmateDataBean inmate) { this.inmate = inmate; } } 

除了扩展EventObject之外,这个类没有什么特别之处。 您的构造函数由EventObject定义,但您可以创建所需的任何方法。

其次,您定义了一个EventListener接口。

 public interface EventListener { public void handleEvent(InmatePhotoEventObject eo); } 

您将使用您创建的EventObject。 您可以使用所需的任何方法名称。 这是代码的接口,将作为对侦听器的响应而编写。

第三,编写一个ListenerHandler。 这是我的同一个项目。

 import gov.bop.rabid.datahandler.bean.InmateDataBean; import gov.bop.rabid.datahandler.main.EventListener; import gov.bop.rabid.datahandler.main.InmatePhotoEventListener; import gov.bop.rabid.datahandler.main.InmatePhotoEventObject; import java.util.ArrayList; import java.util.List; public class InmatePhotoListenerHandler { protected List listeners; public InmatePhotoListenerHandler() { listeners = new ArrayList(); } public void addListener(EventListener listener) { listeners.add(listener); } public void removeListener(EventListener listener) { for (int i = listeners.size() - 1; i >= 0; i--) { EventListener instance = listeners.get(i); if (instance.equals(listener)) { listeners.remove(i); } } } public void fireEvent(final InmatePhotoEventObject eo, final InmateDataBean inmate) { for (int i = 0; i < listeners.size(); i++) { final EventListener instance = listeners.get(i); Runnable runnable = new Runnable() { public void run() { eo.setInmate(inmate); instance.handleEvent(eo); } }; new Thread(runnable).start(); } } public static void main(String[] args) { System.out.println("This line goes in your DataHandlerMain class " + "constructor."); InmatePhotoListenerHandler handler = new InmatePhotoListenerHandler(); System.out.println("I need you to put the commented method in " + "DataHandlerMain so I can use the handler instance."); // public InmatePhotoListenerHandler getInmatePhotoListenerHandler() { // return handler; // } System.out.println("This line goes in the GUI code."); handler.addListener(new InmatePhotoEventListener()); System.out.println("Later, when you've received the response from " + "the web service..."); InmateDataBean inmate = new InmateDataBean(); inmate.setIntKey(23); handler.fireEvent(new InmatePhotoEventObject(handler), inmate); } } 

此类中的主要方法向您展示如何使用ListenerHandler。 该类中的其余方法是标准的。 您将使用自己的EventObject和EventListener。

是。

我建议你看一下ActionEvent和EventListenerList的java API文档。

我还建议您阅读有关Listener(也称为Observer)模式的内容。