我的JavaFX为什么会有此程序流程问题?

问题描述 投票:0回答:1

使用JavaFX和FXML,我试图显示一个包含一些基本信息的屏幕,然后在HTTP调用返回时,更新该屏幕。相反,发生的情况是直到呼叫返回才完全不显示屏幕。以下是对该问题的最小案例测试,其中的延迟旨在模拟HTTP调用。

我希望显示屏幕,更新第一个标签,延迟十秒钟,然后更新第二个标签。取而代之的是,直到延迟结束后才显示屏幕,无论我在何处放置延迟,都会发生这种情况。我希望我忽略了一些简单的事情,而不必创建多个线程来做这么简单的事情。以下是我认为足以回答问题的任何人的代码。如果需要,我可以包含更多代码。

@Override
public void start(Stage stage) throws IOException {

    this.stage = stage;
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(App.class.getResource("primary.fxml"));
    anchroot = (AnchorPane) loader.load();
    // Show the scene containing the root layout.
    Scene scene = new Scene(anchroot);
    stage.setScene(scene);
    // Give the controller access to the main app.
    PrimaryController controller = loader.getController();
    controller.setMainApp(this);
    stage.show();

    //change the first label
    controller.setLabel0();

    //timer to simulate IO
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //try to change the second label 10 sec later
    controller.setLabel1();

}
java maven javafx netbeans fxml
1个回答
1
投票

调用TimeUnit.SECONDS.sleep(10);将使JavaFX线程阻塞10秒钟。在这种情况下,您将无法看到GUI线程中的任何更改,直到睡眠期结束。在JavaFX中,可以使用Timeline在特定时间后进行更新:

controller.setLabel0();
new Timeline(new KeyFrame(Duration.seconds(10), event -> controller.setLabel1())).play();
© www.soinside.com 2019 - 2024. All rights reserved.