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!
When the Application
is launched, the following steps are executed during the launch process:
Application
subclass that should be launched is created. (Constructor is called)init()
of that instance is called.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
andstop
methods have concrete implementations that do nothing.
The differences of constructor, init
and start
are:
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.
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