JavaFX: Calling Event Using Lambda Expression

This entry is part 18 of 55 in the series JavaFX

Java 8 development kit supports Lambda expression.  I was a bit surprised when the default Netbeans program came with a suggestion to use Lambda expression.

As you can see in the screenshot below,


It has this message when you mouse over EventHandler- “This anonymous inner class creation can be turned into a lambda expression”.

A little prodding led me to using -> to call the button click event as shown in the example below.  This arrow operator (->) is a new operator introduced in Java 8 for use with Lambda expressions.

The argument e represents an object of type ActionEvent, which the program can use to get detailed information about the event.

As it is an ActionEvent, we can specify it specifically as in:

btn.setOnAction((ActionEvent e) -> buttonClick());
Action Event
package javafxapplication15;

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;

public class JavaFXApplication15 extends Application {

    Button btn;

    public void start(Stage stage) {
        // Create the button
        btn = new Button();
        btn.setText("New Button");

        //Trigger the button click event
        btn.setOnAction(e -> buttonClick());

        // Add the button to a layout pane
        BorderPane pane = new BorderPane();

        // Add the layout pane to a scenee
        Scene scene = new Scene(pane, 300, 250);

        // Finalize and show the stage
        stage.setTitle("JavaFX Program");;

    public void buttonClick() {
        if (btn.getText() == "Click") {
            btn.setText("Click Click!");
        } else {

    public static void main(String[] args) {




Series Navigation<< JavaFX: Wrapping The Label
JavaFX: Applying Effects To Label >>