Javatpoint Logo
Javatpoint Logo

Event Handlers

JavaFX facilitates us to use the Event Handlers to handle the events generated by Keyboard Actions, Mouse Actions, and many more source nodes.

Event Handlers are used to handle the events in the Event bubbling phase. There can be more than one Event handlers for a single node.

We can also use single handler for more than one node and more than one event type. In this part of the tutorial, we will discuss, how the Event Handlers can be used for processing events.

Adding an Event Handler

Event Handler must be registered for a node in order to process the events in the event bubbling phase. Event handler is the implementation of the EventHandler interface. The handle() method of the interface contains the logic which is executed when the event is triggered.

To register the EventHandler, addEventHandler() is used. In this method, two arguments are passed. One is event type and the other is EventHandler object.

The syntax of addEventHandler() is given below.


In the following example, same event handler is registered with two different buttons. The event source is discriminated in the handle() method. The circle starts translating in the positive X direction when the Play button is clicked while It gets paused when the Pause button is clicked.

JavaFX Event Handlers
JavaFX Event Handlers
JavaFX Event Handlers

Removing EventHandler

when we no longer need an EventHandler to process the events for a node or event types, we can remove the EventHandler by using the method removeEventHandler() method. This method takes two arguments, event type and EventHandler Object.

Next Topic#

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA