很可能您正在事件线程上运行任务,因此它会阻止更新。Task 实现了 Runnable,这有点误导,但通过查看 javadoc,您可以发现运行 Task 的正确方法是将其分配给新线程:new Thread(task).start();
请参见下一个示例:
public class TaskTask extends Application {
public static void main(String[] args) { launch(args); }
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle(VersionInfo.getRuntimeVersion());
Button btn = new Button();
final Task<Integer> task = new Task<Integer>() {
@Override
protected Integer call() throws Exception {
int iterations;
for (iterations = 0; iterations < 100; iterations++) {
if (isCancelled()) {
break;
}
Thread.sleep(100); // imitate activity
updateMessage("Iteration " + iterations);
}
return iterations;
}
};
// here we monitor task updates
btn.textProperty().bind(task.messageProperty());
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
//here it goes
new Thread(task).start();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}