JavaFX Application Life Cycle

The Program LifeCycle.java

Place this in a file named LifeCycle.java.

import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;

public class LifeCycle extends Application
{
    public LifeCycle()
    {
        System.out.println("Constructor is constructing.");
    }
    @Override
    public void init()
    {
        System.out.println("init() is knitting baby booties.");
    }
    @Override
    public void start(Stage primary)
    {
        System.out.println("Start is staring and staying until you quit.");
        System.out.println("Click on the quit button to quit");
        primary.setTitle("JavaFX Appplication Life Cycle Demo");
        Button quit = new Button("Quit");
        quit.setOnAction(e -> Platform.exit());
        BorderPane bp = new BorderPane();
        bp.setTop(quit);
        primary.setScene(new Scene(bp, 500, 500));
        primary.show();
    }
    @Override
    public void stop()
    {
        System.out.println("stop() is mopping up.");
        System.out.println("Program life ends when stop returns (now).");
    }
}

Now run and compile. The window will have a quit button so you can have your terminal back.

unix> javac LifeCycle.java
unix> java LifeCycle
Constructor is constructing.
init() is knitting baby booties.
Start is staring and staying until you quit.
Click on the quit button to quit

What happened?

In general when you create an application, the following occur.

  1. You enter java Example at the command line.
  2. The main method of the application runs, causing the application’s static launch method to run.
  3. The constructor executes.
  4. The init() method executes. By default this does nothing.
  5. The init() method returns and then start() starts to run.
  6. The start method is actually a loop. This loop terminates if the user quits the program, if exception or memory error kills it, or if the start method returns.
  7. If the event that quits the program calls Platform.exit() or if the go- away button is clicked, stop() is called. You can use this method to save or close opened files, or any other housekeeping that should be done prior to shutting down. The stop() method by default does nothing. If the user clicks on the go-away button, the stop() method is also called.
  8. The stop() method returns and the program’s process is terminated. The kernel reclaims the program’s memory and execution ends.