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.
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.
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)
}
}
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;