JavaFx 启动应用程序并继续

JavaFx launch application and continue

我有以下3行代码:

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

问题是当 javafx 应用程序启动时,第 2 行之后的代码直到我关闭 javafx 应用程序才执行。当 javafx 应用程序仍然是 运行 时,启动 javafx 应用程序并执行第 3 行的正确方法是什么?

编辑 1
到目前为止我找到的唯一解决方案是:

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

此解决方案对于 javafx 应用程序是否正常且安全?

我不确定您要做什么,但是 Application.launch 也在等待应用程序完成,这就是为什么您没有立即看到第 3 行的输出的原因。您的应用程序的 start 方法是您要进行设置的地方。有关详细信息和示例,请参阅 the API docs for the Application class

编辑:如果您想从一个主线程运行多个 JavaFX 应用程序,也许这就是您需要的:

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();
    }    
}

这 运行 多个应用程序来自主线程,方法是 运行 在 JavaFX 线程上设置它们的启动方法。但是,您将失去 initstop 生命周期方法,因为您没有使用 Application.launch.