Hello JavaFX World

Posted by Hayri Cicek on October 07, 2019


In this tutorial, we will learn how to create our first JavaFX application.
With JavaFX we can create applications and games, which can run on desktop or mobile devices.


Hello JavaFX World

The following example shows how to create our first JavaFX application.
Open your IDE or a Text Editor of your choice, and create a new file HelloJavaFXWorld.java and type in the following.


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

public class HelloJavaFXWorld extends Application {

    @Override
    public void start(Stage stage) {
        Label label = new Label("Hello JavaFX World");
        Scene scene = new Scene(new StackPane(label), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}


Each JavaFX application must extend the Application class and implement the start() method.
The start() method is the main entry point of any JavaFX application and has Stage as its only parameter, which is the main window.
StachPane is the container for organizing nodes.
We are calling the static method launch() of the Application class from the main method to launch our JavaFX application.

How to run the code:

You can find more options how to create and run JavaFX applications here.

JDK 8:

$ javac HelloJavaFXWorld.java
$ java HelloJavaFXWorld


JDK 13:

Download JavaFX runtime https://gluonhq.com/products/javafx/ for your operating system and unzip it to a desired location.
Add an environment variable pointing to to the JavaFX runtime lib.

Linux/macOS:

export JAVA_FX_RUNTIME_PATH=/javafx_runtime_path/javafx-sdk-13/lib
javac --module-path $JAVA_FX_RUNTIME_PATH --add-modules javafx.controls HelloJavaFXWorld.java
java --module-path $JAVA_FX_RUNTIME_PATH --add-modules javafx.controls HelloJavaFXWorld


Windows

set JAVA_FX_RUNTIME_PATH="\javafx_runtime_path\javafx-sdk-13\lib"
javac --module-path %JAVA_FX_RUNTIME_PATH% --add-modules javafx.controls HelloJavaFXWorld.java
java --module-path %JAVA_FX_RUNTIME_PATH% --add-modules javafx.controls HelloJavaFXWorld




The code is available on GitHub.
In this quick tutorial we learned how to create and run our first JavaFX application.


Share this: