如何发布和处理自定义事件? [英] How to emit and handle custom events?

查看:131
本文介绍了如何发布和处理自定义事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

一般来说:


  1. 创建所需的 EventType

  2. 创建相应的事件

  3. 致电 Node.fireEvent()

  4. 添加处理程序和/或过滤器

  1. Create a desired EventType.
  2. Create the corresponding Event.
  3. Call Node.fireEvent().
  4. Add Handlers and/or Filters for EventTypes of interest.

一些解释:

如果你要创建一个事件级联,从所有或任何类型开始,这将是所有EventTypes的根目录:

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 class 事件)。 EventTypes应该输入到这个事件类(就像我的例子)。

Then write the MyEvent class (which extends Event). The EventTypes should be typed to this event class (as is my example).

现在使用(或换句话说:fire)事件:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆