如何发出和处理自定义事件? [英] How to emit and handle custom events?
问题描述
javafx 中有几个预定义的事件类.Event.ANY、KeyEvent.KEY_TYPED、MouseEvent.ANY 等等.还有先进的事件过滤和处理系统.我想重用它来发送一些自定义信号.
There are several predefined event classes in javafx. Event.ANY, KeyEvent.KEY_TYPED, MouseEvent.ANY and so on. There is also advanced filtering and handling system for events. And I'd like to reuse it to send some custom signals.
如何创建自定义事件类型 CustomEvent.Any,以编程方式发出此事件并在节点中处理它?
How can I create my custom event type CustomEvent.Any, emit this event programmatically and handle it in a node?
推荐答案
一般:
- 创建所需的EventType.
- 创建相应的事件.
- 调用 Node.fireEvent().
- 添加处理程序 和/或 过滤器,用于感兴趣的事件类型.
- Create a desired EventType.
- Create the corresponding Event.
- Call Node.fireEvent().
- Add Handlers and/or Filters for EventTypes of interest.
一些解释:
如果要创建事件级联,请从All"或Any"类型开始,这将是所有 EventType 的根:
If you want to create an event cascade, start with an "All" or "Any" type, that will be the root of all of the EventTypes:
EventType<MyEvent> OPTIONS_ALL = new EventType<>("OPTIONS_ALL");
这使得创建这种类型的后代成为可能:
This makes possible creating descendants of this type:
EventType<MyEvent> BEFORE_STORE = new EventType<>(OPTIONS_ALL, "BEFORE_STORE");
然后编写MyEvent
类(它扩展了Event
).EventTypes 应该输入到这个事件类中(就像我的例子一样).
Then write the MyEvent
class (which extends Event
). The EventTypes should be typed to this event class (as is my example).
现在使用(或换句话说:触发)事件:
Now use (or in other words: fire) the event:
Event myEvent = new MyEvent();
Node node = ....;
node.fireEvent(myEvent);
如果你想抓住这个事件:
If you want to catch this event:
Node node = ....;
node.addEventHandler(OPTIONS_ALL, event -> handle(...));
node.addEventHandler(BEFORE_STORE, event -> handle(...));
这篇关于如何发出和处理自定义事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!