Search code examples
javajavafxscenestage

JavaFX - What is the point of the Stage argument?


I am going through this tutorial: https://docs.oracle.com/javase/8/javafx/get-started-tutorial/hello_world.htm

And it says this:

"A JavaFX application defines the user interface container by means of a stage and a scene. The JavaFX Stage class is the top-level JavaFX container. The JavaFX Scene class is the container for all content..."

"In JavaFX, the content of the scene is represented as a hierarchical scene graph of nodes. In this example, the root node is a StackPane object..."

I don't understand what the point of the Stage object is. If the StackPane is the root node (and I understand the whole tree structure thing), and if the Scene is the container for all content, what is the Stage doing? Why can't what it does be done by the Scene?

Here is the code:

public class HelloWorld extends Application {

    @Override
    public void start(Stage primaryStage) {
        // TODO Auto-generated method stub
        Button btn = new Button("Say 'Hello World'");
        btn.setOnAction((ActionEvent event) -> System.out.println("Hello World!"));

        StackPane root = new StackPane();
        root.getChildren().add(btn);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

}

Solution

  • It's basically a seperation of concerns.

    Stage is a object for modifying the look, title, position ect. of the window, Scene is used for layouting and handling events ect..

    Implementing the functionality in seperate classes is a design decision which is most likely also influenced by the fact that a window is provided by the OS and the scene if completely rendered by the toolkit inside the window provided.

    However Scene can be used in containers used to embed JavaFX in other GUI libraries as well (FXCanvas, JFXPanel).