JavaFx in Groovy

HelloWorld Javafx application in groovy

We are not going to use GroovyFX or any other syntax, but simply write JavaFX application in groovy. The purpose of using groovy is to reduce the verbose code that needs to be declared for creating UI and defining events.

JavaFX Events with groovy closures

For example below JavaFX code for handling button click event

btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});

can be written in groovy with closures.

btn.setOnAction({
    event -> System.out.println("Hello World!")
});

For a UI application, we need to write a ton of event listeners. Having closures helps in reducing the verbose code.

Defining ui elements

def btn, txtBox
btn = new Button()
def root = new StackPane()

It is easier to define UI elements and assign values to them later when needed.

We are going to convert the this JavaFx HelloWord example to Groovy.

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

class HelloWorld extends Application {

    void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!")
        def btn = new Button()
        btn.setText("Say 'Hello World'")
        btn.setOnAction({
            event -> System.out.println("Hello World!")
        })

        def root = new StackPane()
        root.getChildren().add(btn)
        primaryStage.setScene(new Scene(root, 300, 250))
        primaryStage.show()
    }

    static void main(String[] args) {
        launch(HelloWorld, args)
    }
}

Advantages of Writing JavaFX in Groovy

We can save this file with any name. There is no need to save with same class name HelloWorld.groovy If you notice in the above code, there was no need to import ActionEvent or EventHandler.

//import javafx.event.ActionEvent;
//import javafx.event.EventHandler;
  • Less lines of code means lesser code maintenance.
  • Less we type, the faster we develop.
  • Even with code-completion, we need to write lesser code