JavaFX Tutorial – We shall learn to Create new Button and Set Action Listener in JavaFX Application.
In JavaFX, a button click is handled by assigning an action handler to the Button using setOnAction(). This is similar in purpose to an action listener, but JavaFX uses the EventHandler<ActionEvent> event model instead of the Swing ActionListener API. The example below creates a button, places it in a StackPane, and prints a message when the user clicks the button.
Create new Button and Set Action Listener in JavaFX
Following is a quick code snippet to create a Button and set action listener to this Button.
Quick Code Snippet
Button btn = new Button();
btn.setText("Display Message");
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hi there! You clicked me!");
}
});
The same JavaFX button action handler can also be written using a lambda expression in modern Java. The lambda form is shorter and is commonly used when the click action has only a few statements.
Button btn = new Button("Display Message");
btn.setOnAction(event -> {
System.out.println("Hi there! You clicked me!");
});
Both versions attach code to the same JavaFX button click event. The anonymous class version is easier for beginners to see step by step, while the lambda version is concise.
JavaFX Button Click Handler Prerequisites
Before writing the example program, make sure that your project can run a basic JavaFX application. You should have a JDK, JavaFX libraries or OpenJFX configured, and a Java class that extends Application. For reference, the official JavaFX Button API documentation describes the Button class and its inherited event properties.
Following is a step by step guide to create a new Button in JavaFX and Set Action Listener.
1 Create a JavaFX Button Object
Import javafx.scene.control.Button class and create a new object of this class type.
Button btn = new Button();
You may also pass the button label directly to the constructor if you already know the text.
Button btn = new Button("Display Message");
2 Set Text on the JavaFX Button
Set text for the JavaFX Button using Button.setText() method.
btn.setText("Display Message");
The text appears as the visible label inside the button. Keep the label short and action-oriented so that the user can understand what the button does.
3 Set Action Listener for JavaFX Button Click
If you have set an Action Listener and the button is clicked, EventHandler would execute the handle method. You should implement the handle method to perform an action after an event happens for button.
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hi there! You clicked me!");
}
});
The event object passed to handle(ActionEvent event) contains information about the action event. In a button click example, you normally use the handler to update the UI, print a message, open another screen, submit a form, or call another method.
Anonymous EventHandler vs Lambda for JavaFX Button Action
The original example uses an anonymous EventHandler class. This form clearly shows the handle() method that JavaFX executes when the button is clicked. The lambda expression below does the same job with less code.
btn.setOnAction(event -> System.out.println("Hi there! You clicked me!"));
Use the anonymous class form when teaching the event-handling structure. Use the lambda form when writing compact application code. Both are valid JavaFX ways to respond to a button action.
4 Run the JavaFX Button Action Listener Application
Following is the complete program to set action listener to JavaFX Button.
NewButtonExample.java
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class NewButtonExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
try {
// set title
primaryStage.setTitle("New Button and its Action Listener");
// create a new Button shape
Button btn = new Button();
// set text inside button
btn.setText("Display Message");
// set Action Listener
btn.setOnAction(new EventHandler() {
@Override
public void handle(ActionEvent event) {
// instructions executed when the button is clicked
System.out.println("Hi there! You clicked me!");
}
});
// stack pane
StackPane root = new StackPane();
// add button to Stack Pane
root.getChildren().add(btn);
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
}
The program creates the button inside the start() method because JavaFX UI nodes should be created and updated on the JavaFX Application Thread. The StackPane is used as the root layout and places the button at the center of the window by default.
GUI Output
Following would be the output on running the JavaFX Application.

If you click on the button ‘Display message’, ‘Hi there! You clicked me!’ would be printed to console output. You may replace the code in handle() method to perform your own defined action.
Console Output
Hi there! You clicked me!
JavaFX Button Click Flow in This Example
The button click flow is simple:
- The JavaFX runtime opens the primary stage.
- The program creates a
Buttonand sets its text. - The program registers a handler using
btn.setOnAction(...). - The button is added to the
StackPane. - When the user clicks the button, JavaFX fires an
ActionEvent. - The registered handler runs and prints the message to the console.
Update Label Text Instead of Printing Console Output
Console output is useful for learning, but most JavaFX applications update the screen when the user clicks a button. The following small example changes a label when the button is clicked.
Label messageLabel = new Label("Click the button");
Button btn = new Button("Display Message");
btn.setOnAction(event -> {
messageLabel.setText("Hi there! You clicked me!");
});
For this snippet, import javafx.scene.control.Label along with Button. In a full program, add both the label and the button to a layout such as VBox or StackPane.
Common JavaFX Button Action Listener Errors
| Issue | Cause | Fix |
|---|---|---|
| Button appears but click does nothing | No handler is assigned to setOnAction() | Call btn.setOnAction(...) before or after adding the button to the layout. |
ActionEvent or EventHandler cannot be resolved | Missing imports | Import javafx.event.ActionEvent and javafx.event.EventHandler. |
Using Swing ActionListener in JavaFX code | Mixing Swing event API with JavaFX | Use JavaFX EventHandler<ActionEvent> or a lambda with setOnAction(). |
NullPointerException near application.css | The CSS file is missing in the expected package | Create application.css or remove the stylesheet line until styling is required. |
| UI freezes after button click | Long-running work is executed directly inside the click handler | Move long-running work to a background task and update the UI safely afterward. |
JavaFX Button Action Listener QA Checklist
Use this checklist to review the JavaFX button example before publishing or debugging it:
- The example imports
javafx.scene.control.Button. - The button text is set using the constructor or
setText(). - The click action is registered using
setOnAction(). - The handler uses JavaFX
ActionEvent, not SwingActionListener. - The button is added to a visible layout node such as
StackPane. - The layout node is set as the root of a
Scene. - The scene is set on the
Stageand the stage is shown. - The console output is checked after clicking the button.
- Any CSS file reference points to an existing resource.
- Long operations are not placed directly inside the button click handler.
FAQs on JavaFX Button and Action Listener
How do I add an action listener to a JavaFX Button?
Use the setOnAction() method of the Button class. You can pass an anonymous EventHandler<ActionEvent> or a lambda expression. The handler code runs when the button is clicked or activated.
Is JavaFX ActionListener the same as Swing ActionListener?
No. Swing uses java.awt.event.ActionListener, while JavaFX uses javafx.event.EventHandler with ActionEvent. For a JavaFX button, use btn.setOnAction(...).
Can I use a lambda expression for JavaFX button click events?
Yes. A lambda expression is a common way to write JavaFX button click code. For example, btn.setOnAction(event -> System.out.println("Clicked")); registers a simple click handler.
Why is my JavaFX button click not printing anything?
Check that setOnAction() is called on the same button that is added to the scene. Also verify that you are looking at the IDE console, because System.out.println() prints to the console, not to the JavaFX window.
Where should I put JavaFX button click code?
For a small example, place the click handler inside the start() method after creating the button. For larger applications, call a separate method from the handler so that the UI code remains easier to read and maintain.
Conclusion: JavaFX Button with Action Handler
In this JavaFX Tutorial : Create new Button and Set Action Listener in JavaFX , we have learnt to create a new button with desired text and trigger an action when the button is clicked. The key method is setOnAction(), which connects a JavaFX button to the code that should run after the click event.
TutorialKart.com