ayvango ayvango - 1 year ago 64
Java Question

How to emit and handle custom events?

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.

How can I create my custom event type CustomEvent.Any, emit this event programmatically and handle it in a node?

Answer Source

In general:

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

Some explanations:

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");

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

Now use (that is, fire) the event:

Event myEvent = new MyEvent();
Node node = ....;

To catch this event:

Node node = ....;
node.addEventHandler(OPTIONS_ALL, event -> handle(...));
node.addEventHandler(BEFORE_STORE, event -> handle(...));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download