Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX Application class - difference between default constructor and init method

Tags:

java

javafx

I have written a little test application that looks like this:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;

public class Test extends Application {

    public Test() {
        System.out.println("first");
    }

    @Override
    public void init() throws Exception {
        System.out.println("second");
        super.init();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        System.out.println("third");
        Platform.exit();
    }

    @Override
    public void stop() throws Exception {
        System.out.println("fourth");
        super.stop();
    }

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

The output is:

first
second
third
fourth

Now, I am asking myself where the difference is between using the default constructor or the init method for initialising some required things.

Thanks!

P.S.: This question is not duplicate with this one, because my issue does not handle the initialisation of variables. My question is JavaFX specific!

like image 238
mrbela Avatar asked Sep 03 '25 15:09

mrbela


1 Answers

When the Application is launched, the following steps are executed during the launch process:

  1. The instance of the Application subclass that should be launched is created. (Constructor is called)
  2. The init() of that instance is called.
  3. The start method of that instance is called.

See javadoc for Application

Since you exit the application after the start method is called, the stop method of the instance is called.

Note that there is no need to use super.init() and super.stop():

From the javadoc

The init and stop methods have concrete implementations that do nothing.



The differences of constructor, init and start are:

Constructor

If your application is not final the application class could be extended. Since the constructor of the extending class is not complete, it may be dangerous to pass a reference to the class to other classes in this state. Also the instance hasn't been initialized to a point where the getParameters method returns the parameters.

init

Initialisation should generally be done in this method. This method isn't run from the fx application thread, so some things cannot be done from this method, like creating a Stage.

start

Last step in the initialisation. Do things that require to be run from the application thread here. Be careful not to block this thread with long-runing operations however, since this freezes the GUI.

like image 134
fabian Avatar answered Sep 05 '25 07:09

fabian