user2022068
user2022068

Reputation:

JavaFx launch application and continue

I have the following 3 lines of code:

1 System.out.println("Starting program...");
2 Application.launch((Gui.class));
3 System.out.println("Continuing program...");

The problem is that when javafx application started the code after line 2 is not executed until I close javafx application. What is the right way to start javafx application and execute line 3 when javafx application is still running?

EDIT 1
The only solution I found up till now is:

2 (new Thread(){
      public void run(){
        Application.launch((Gui.class));
       }
  }).start();

Is this solution normal and safe for javafx application?

Upvotes: 2

Views: 4321

Answers (1)

Steven Van Impe
Steven Van Impe

Reputation: 1163

I'm not sure what you're trying to do, but Application.launch also waits for the application to finish which is why you're not seeing the output of line 3 immediately. Your application's start method is where you want to do your setup. See the API docs for the Application class for more information and an example.

Edit: if you want to run multiple JavaFX apps from a main thread, maybe this is what you need:

public class AppOne extends Application
{
    @Override
    public void start(Stage stage)
    {
        Scene scene = new Scene(new Group(new Label("Hello from AppOne")), 600, 400);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args)
    {
        System.out.println("Starting first app");
        Platform.runLater(() -> {
            new AppOne().start(new Stage());
        });
        System.out.println("Starting second app");
        Platform.runLater(() -> {
            new AppTwo().start(new Stage());
        });
    }
}

public class AppTwo extends Application
{
    @Override
    public void start(Stage stage)
    {
        Scene scene = new Scene(new Group(new Label("Hello from AppTwo")), 600, 400);
        stage.setScene(scene);
        stage.show();
    }    
}

This runs multiple apps from the main thread by running their start methods on the JavaFX thread. However, you will lose the init and stop lifecycle methods because you're not using Application.launch.

Upvotes: 3

Related Questions