12.4. Mid-Level Walkthrough

Now, let’s go back to ExampleApp.java. Inspect the start method, which is required to be overridden in concrete subclasses of the Application class. The start method is considered the main entry point for a JavaFX application. It is called after the init method has returned and after the system is ready for the app to begin running.

The start method’s only parameter is a reference to a Stage object. The JavaFX Stage class is the top level JavaFX container (i.e., consider it to be the window). The primary Stage is constructed by the platform during step 3 of the JavaFX application life-cycle. Additional Stage objects may be constructed by the application.

By default, a stage is not visible. You must initialize it with a reference to a Scene object before making it visible. You should refer to the API documentation for the Stage class about different properties a stage can have, including decorations and modality options. In the starter code, you will notice a call to stage.show() at the end of the start method that makes the stage visible.

In JavaFX, a scene is the container for all content in the window (also called the scene graph). The term “scene graph” is just a fancy term for a structured hierarchy of the nodes/components contained in a particular scene. We use the term “node” because all such objects have an upper bound of javafx.scene.Node.

  • There can only be one Scene on a Stage at a time, and a Scene can only be on one Stage at a time.

  • You may swap scenes on a Stage at any time so long as the call to setScene is made on the JavaFX Application Thread (more on this later).

One reason that JavaFX employs the use of scenes instead of directly adding nodes/components to a stage is to enable easier swapping between modes of an app. For example, consider a video game with a title screen, main game screen, and an options screen. In this scenario, each “screen” might be its own scene.

The scene graph for the ExampleApp is small and would look like this:

root: HBox
    |
hello: Text

The “root” of this scene graph is an object of the HBox container class. This object has one child, an object of the Text class.

Before you continue, you should note what each line in the start method of ExampleApp.java is doing by referring to the corresponding API documentation. This is something that you will be doing a lot while working with JavaFX (and most other libraries).

The scene graph was given in the previous step. You might also find the overall containment hierarchy for ExampleApp helpful. It would look something like this:

stage: Stage
     |
scene: Scene
     |
root: HBox
     |
hello: Text

The “root” of the containment hierarchy is an object of the Stage container class. The stage object contains the Scene.