简体   繁体   English

JavaFX从另一个线程更新UI

[英]JavaFX Updating UI from another thread

I have a main class 我有一个主班

    public class Main {
        public static void main(String[] args) {
            Application.launch(View.class);
            View view = new View();
            Platform.runLater(() -> view.changeTitle());
        }
    }

and a view JavaFX class 和一个视图JavaFX类

    public class View extends Application {

        Stage primaryStage;

        public View() {

        }

        @Override
        public void start(Stage primaryStage) throws Exception{
            Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
            primaryStage.setTitle("Hello World");
            primaryStage.setScene(new Scene(root, 300, 275));
            this.primaryStage = primaryStage;
            primaryStage.show();
        }

        public void changeTitle() {
           primaryStage.setTitle("YEA!");
       }
    }

I want the main class to do something in JavaFX thread but my code doesn't work. 我希望主类在JavaFX线程中执行某些操作,但是我的代码无法正常工作。 In documentation said that I can call Platform.runLater() from any thread I want. 在文档中说我可以从我想要的任何线程调用Platform.runLater()。 If I call Platform.runLater() from JavaFX thread (in start(), for example), everything is OK. 如果我从JavaFX线程(例如,在start()中)调用Platform.runLater(),一切正常。

First, main(String) is blocked on Application.launch(Class) . 首先, main(String)Application.launch(Class)上被阻止。

From Oracle Javadocs: 从Oracle Javadocs:

The launch method does not return until the application has exited, either via a call to Platform.exit or all of the application windows have been closed. 直到调用退出Platform.exit或关闭了所有应用程序窗口后,启动方法才返回。

Second, you're creating a new View instance on the second line. 其次,在第二行上创建一个新的View实例。 That will NOT be same instance Application created, so your Platform.runLater wouldn't affect the launched application even if that code were reachable before it exited. 那将不是同一实例应用程序创建的,因此即使退出该代码之前可以访问已启动的应用程序,您的Platform.runLater也不会对其产生影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM