- COMP.CS.140
- 12. Graphical User Interfaces
- 12.2 JavaFX Library
JavaFX Library¶
JavaFX is a JavaAPI for implementing graphical user interfaces. It comes directly with the Java SE Runtime Environmentia (JRE) and the JDK. JavaFX tutorial is a useful resource when implementing JavaFX programs.
In NetBeans a JavaFX program can be implemented as a Maven project with New Project->Simple JavaFX Maven Archetype.
The pom.xml
of a JavaFX project should contain a dependency for JavaFX. For example:
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17.0.1</version>
</dependency>
</dependencies>
and a plugin definition for a JavaFX Maven plugin. For example:
<plugins>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.8</version>
<configuration>
<mainClass>package.MainClass</mainClass>
</configuration>
</plugin>
</plugins>
The MainClass
defined contains the class that defines the JavaFX program.
NetBeans populates an initial class directly but the simplest JavaFX program is:
package example;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
* JavaFX App
*/
public class App extends Application {
@Override
public void start(Stage stage) {
// Setting the main window with a title
stage.setTitle("All the world's a stage");
// Show the main window
stage.show();
}
public static void main(String[] args) {
launch( args );
}
}
Let’s break the program structure into peaces to see what makes a JavaFX program.
The main class of a JavaFX program derives from a javafx.application.Application
class.
When the program starts the program execution goes forward on the main class level:
The defined
Application
class is instantiatedThe
init()
method that initializes the state the program needs to have before execution starts. For example creates objects needed.Calls the
start(Stage stage)
method that acts as the starting point for the program The method receivesjavafx.stage.Stage
object that defines the program main window as a parameter. Calling theshow()
method for thestage
shows the window on the screen.The program stays here and listens for the events. The main class waits here for a program closing event i.e. either a call for
Platform.exit()
or that all windows are closed withimplicitExit
forPlatform
Calls the
stop()
method
It is important to note that start()
is abstract in Application
and must be overriden.
Empty implementations are provided for init()
and stop()
.
Our program does nothing so far. Let’s add functionality to the window.