Project Creation
Although this will be kept as simple as possible, we will use Gradle for this Project. If you know what you are doing you can keep Gradle out of this and use your own build pipeline and directory structure. If not, start with creating the following directories:
src
└── main
└── java
└── hello
└── resources
└── ui
Since we are using Gradle to build the application, create a build.gradle
in the top
directory (next to the src
folder):
apply plugin: "java"
jar {
manifest {
attributes "Main-Class": "hello.Main"
}
}
This tells Gradle to use the java compilation plugin and that the created
jar-file will execute the hello.Main
class.
We will start with the implementation of that class. Add it in src/main/java/hello/Main.java
:
package hello;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
// Load the FXML contents
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("ui/main.fxml"));
// Setup a window to show that view in
primaryStage.setTitle("Hello World");
primaryStage.setScene(new Scene(root, 300, 200));
primaryStage.show();
}
}
What's happening here
- As we create a JavaFX application we subclass
javafx.application.Application
. - As this class is also the entry point for our application we add the
main()
function that makes this class executable. - In that function we only call
launch(args)
which comes from subclassingApplication
to start the JavaFX window creation. - We override the
start()
function to fill our window (primaryStage
) with a view:- The view is loaded from the
ui/main.fxml
file via theFXMLLoader
class. - The stage receives a title and a new
Scene
with the loaded view and a width and height of 300 by 200 pixels. - Show the window. This call will block at that line until the window is closed.
- The view is loaded from the
Continue with the view.
Why is it called Stage and not Window?
JavaFX is not only targeted at desktop applications but also very much at web applications. A stage would then be the element within the web site that contains the JavaFX UI. But when developing for desktop applications the stage object can be seen as the window. You set the window style on it, the modality and the optional parent-window when creating a dialog.