使用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();
}
答案 0 :(得分:2)
调用TimeUnit.SECONDS.sleep(10);
将使JavaFX
线程阻塞10秒钟。在这种情况下,您将无法看到GUI线程中的任何更改,直到睡眠期结束。在JavaFX中,您可以使用Timeline
在特定时间段后进行更新:
controller.setLabel0();
new Timeline(new KeyFrame(Duration.seconds(10), event -> controller.setLabel1())).play();