How to use setOnAction in JavaFX

In this tutorial we will teach you how to use setOnAction in JavaFX. This method is used together with several other Interfaces and Functions in JavaFX to generate and handle “events”. setOnAction() is not limited to a particular widget, though it’s use is most commonly seen with the “button” widget.

There are multiple ways of implementing setOnAction() in JavaFX. We will be discussing the most easiest, convenient and modern approach to this problem. Let’s get started!


JavaFX setOnAction

First, we need to make a few customary imports. The stage and scene are mandatory in any JavaFX application, we need a Button on which we will call setOnAction(), and a layout to store this button in.

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;

We will first setup our application as follows.

public class Tutorial extends Application {
	public static void main(String args[]){          
		 launch(args);     
	}
	
	@Override     
	public void start(Stage primary) throws Exception { 
		StackPane layout = new StackPane();
		Scene scene = new Scene(layout, 300, 300);
		
		Button button = new Button("Click Me!");
		layout.getChildren().addAll(button);
		
		primary.setTitle("setOnAction() Tutorial");
		primary.setScene(scene);	
		primary.show();
    }
}

Now that we have our basic window setup, we can move on to Event Handling part.


It is finally time to use the setOnAction() method.

button.setOnAction(e -> System.out.println("Hello World"));

What we have done here, is passed an anonymous function (also known as lambda function) inside the setOnAction method. Basically what we are saying here, is that every time an action is performed on the button (mouse click) this function should be called which prints hello world.

The above variant is a short hand way of writing one-line lambda functions. Here is the full form.

button.setOnAction(e -> {
    System.out.println("Hello World");
    System.out.println("Hello World Again");
});

And that’s all! You can also choose to call another user-defined function inside this lambda function if you want. The “e” in the lambda function is actually an event object, which you may or may not need. (It contains information about the event, and varies from action to action).


This marks the end of the How to use setOnAction in JavaFX Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments