JavaFx启动应用程序并继续 [英] JavaFx launch application and continue

查看:170
本文介绍了JavaFx启动应用程序并继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下3行代码:

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

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

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?

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

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

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

对于Javafx应用程序来说,此解决方案是否正常且安全?

Is this solution normal and safe for javafx application?

推荐答案

我不确定您要做什么,但是Application.launch还要等待应用程序完成,这就是为什么您看不到立即输出第3行.应用程序的start方法是您要进行设置的地方.请参阅 Application类的API文档以了解更多信息和示例.

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.

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

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

这通过在JavaFX线程上运行启动方法来从主线程运行多个应用程序.但是,您将丢失initstop生命周期方法,因为您没有使用Application.launch.

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.

这篇关于JavaFx启动应用程序并继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆