How to Add Event Handling in JavaFX


In this article, we show how to add event handling in JavaFX.

This is an important programming because by itself any element added to a stage in JavaFX such as a button is pretty much pointless unless you add functionality to it. If you don't add functionality to a button or any other type of object, then it doesn't do anything when a user clicks on it. So it doesn't serve a purpose.

It only serves a purpose when it's linked to an event handler that can do something when the button.

We will show how to do this in JavaFX in the easiest manner possible, using lambda expressions.

Lamba expressions in Java makes event handling a very, very simple task.

We will show how to do this right below.

In the code below, we create a stage and a scene with a button in it. We then add event handler so that when the button is clicked, it changes text. The button originally states, "Submit Answer" to "You've submitted the answer".

So this is the code shown below.

So just like any JavaFX application, you need to import several packages. You're more than likely familiar with this.

We then create a class that extends the Application. Therefore, we inherit all the functionality of the Application class, which has a lot of classes and methods that we need to use.

We set the title to "Exam Questions".

We then create an instance of the Button class, which represents a button, named button. We give the button a text value of "Submit Answer".

The next line now is where we have event handling using lambda expressions.

So we use the Java function setOnAction and then inside of this function (as the parameter), we pass in, e -> button.setText("You've submitted an answer");

What this does is when the button is click, the e parameter acts as an event handler for the event that has been triggered (button click). What comes after the "->" is what is done when this event is triggered. In this case, we change the text of the button to "You've submitted an answer".

And this is all that is required to add event handling to any type of element on a JavaFX scene.

If you want multiple actions done for an event, then you would add curly braces. So, for example, if we want to add 2 statements, you would use curly braces, such as what is shown below.

So this now enables you to add multiple statements to execute on event handling.

And this is all that is required to add event handling in JavaFX.

Related Resources

How to Add a Title to a Window Using JavaFX

HTML Comment Box is loading comments...