How to emit and handle custom events?

ayvango picture ayvango · Dec 11, 2014 · Viewed 26.4k times · Source

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

eckig picture eckig · Dec 11, 2014

In general:

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

Some explanations:

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

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(...));