What is JavaFX Scene
The JavaFX Scene class is the container for all the contents of a JavaFX application. The scene in the JavaFX application handles the nodes in the JavaFX application. The class Scene comes from the package javafx.scene.
How to show the JavaFX scene
To show the JavaFX scene, you need to instantiate the Scene class. While instantiating, you need to pass the root object to the constructor of the scene class.
Scene scene = new Scene(parentRoot);
Steps in showing the JavaFX Scene and creating a window
Create a Java class and extends the Application class and implement the start method. Please refer to the following code below. Create a group object. On my side, I’m gonna use a BorderPane Layout.
BorderPane root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Creating a Scene object and pass the root object to the constructor of the Scene class to show the JavaFX Scene.
Scene scene = new Scene(root);
Setting the title of the Stage. To set the title of the Stage, we need to use the setTitle() method of the Stage class.
stage.setTitle("Kensoft PH");
Add the scene object to the Stage by using the setScene() method of the Stage class.
stage.setScene(scene);
To show the JavaFX Scene, you will also need to show the stage. We will just use the show() method of the Stage class.
stage.show();
Lastly, launching the application.
public static void main(String[] args) { launch(args); }
Example code
In this example code, we will run a JavaFX application. Please be aware that it will run if you have content in your FXML file.
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Responsive extends Application { @Override public void start(Stage stage) throws Exception { BorderPane root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml")); Scene scene = new Scene(root); stage.setTitle("Kensoft PH"); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } }
Output
This is my output based on my FXML file.