The starting point for a JavaFX application is start method. But in the sample JavaFX applications, there is a main method included as well. What is the use of main method in this particular case and why was there a need to define start() as starting point for JavaFX. Couldn't we simply use the main method to define a starting point like Swings?
A sample HelloWorld application:
public class HelloWorld extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Hello World");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(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);
}
}
The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file.
It is represented by Stage class of the package javafx. stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section).
The start() method is called. The launcher waits for the application to finish and calls the stop() method.
From Oracle Docs ,
The main() method is not required for JavaFX applications when the JAR file for the application is created with the JavaFX Packager tool, which embeds the JavaFX Launcher in the JAR file. However, it is useful to include the main() method so you can run JAR files that were created without the JavaFX Launcher, such as when using an IDE in which the JavaFX tools are not fully integrated. Also, Swing applications that embed JavaFX code require the main() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With