Understanding JavaFX Event Types
by
, 12-11-2016 at 06:41 PM (2111 Views)
In JavaFX, every event generated within an application has a type, which is represented by the EventType<T extends Event> class. An EventType<T> object represents a specific type of event within the T Event subclass. To identify common event types, most Event subclasses in JavaFX contain a set of static constants representing the different types of events within a given subclass. For example, the MouseEvent class contains static constants such as MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED, and so on.
Event types form a hierarchy of supertypes and subtypes: every EventType object has a supertype, excluding the root of the hierarchy, identified by the Event.ANY constant, which is the only event type without a supertype. For example, MouseEvent.MOUSE_PRESSED is subtype of MouseEvent.ANY, which in turn is a subtype of InputEvent.ANY, which is a subtype of Event.ANY.
The event type hierarchy generally follows to some extent the class relationships between the Event base class and its (direct or indirect) subclasses: for example, the type hierarchy mentioned above is related to the MouseEvent → InputEvent → Event class relationship. Event types are useful because they make it easy to specify different types within an Event subclass without subclassing that subclass: in the case of mouse events, the different types such as e.g. MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED, and so on, are simply defined as static constants within the MouseEvent class.
Event types are used when defining event handlers and event filters: for example, the method in the Node class which allows adding a handler for all events reaching a given node in a scene graph is defined as <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler). The eventType argument indicates the type of events that the eventHandler argument wants to receive; the T type parameter is the Event subclass to which the event type refers. The following code snippet demonstrates how to register a handler for all events indicating a release of a mouse button when the mouse cursor is positioned over a given node in the scene graph:
An event handler registered for a given event type receives all events of that type and its subtypes: for example, a handler registered to receive events of type MouseEvent.ANY will receive all mouse events of type MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED, and so on.Java Code:myNode.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { public void handle(MouseEvent e) { // All events delivered here have MouseEvent.MOUSE_RELEASED // as event type. } });