The Basic Structure of a JavaFX Program

paulike

Paul Ngugi

Posted on June 20, 2024

The Basic Structure of a JavaFX Program

The abstract javafx.application.Application class defines the essential framework for writing JavaFX programs. We begin by writing a simple JavaFX program that illustrates the basic structure of a JavaFX
program. Every JavaFX program is defined in a class that extends javafx.application.Application, as shown in the program below:

Image description

Image description

The launch method (line 23) is a static method defined in the Application class for launching a stand-alone JavaFX application. The main method (lines 22–24) is not needed if you run the program from the command line. It may be needed to launch a JavaFX program from an IDE with a limited JavaFX support. When you run a JavaFX application without a main method, JVM automatically invokes the launch method to run the application.

The main class overrides the start method defined in javafx.application.Application (line 9). After a JavaFX application is launched, the JVM constructs an instance of the class using its no-arg constructor and invokes its start method. The start method normally places UI controls in a scene and displays the scene in a stage, as shown in Figure below (a).

Image description

Line 11 creates a Button object and places it in a Scene object (line 12). A Scene object can be created using the constructor Scene(node, width, height). This constructor specifies the width and height of the scene and places the node in the scene.

A Stage object is a window. A Stage object called primary stage is automatically created by the JVM when the application is launched. Line 14 sets the scene to the primary stage and line 15 displays the primary stage. JavaFX names the Stage and Scene classes using the analogy from the theater. You may think stage as the platform to support scenes and nodes as actors to perform in the scenes.

You can create additional stages if needed. The JavaFX program in program below displays two stages, as shown in Figure above (b).

Image description

Note that the main method is omitted in the listing since it is identical for every JavaFX application. From now on, we will not list the main method in our JavaFX source code for brevity.

By default, the user can resize the stage. To prevent the user from resizing the stage, invoke stage.setResizable(false).

πŸ’– πŸ’ͺ πŸ™… 🚩
paulike
Paul Ngugi

Posted on June 20, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related