JavaFx launch application and continue

荒凉一梦 提交于 2019-12-24 15:35:22

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/30443322/javafx-launch-application-and-continue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!