在不同于Thread
a的情况下执行此Task
操作,更新进度并将进度属性绑定到 的进度Task
:
@Override
public void start(Stage primaryStage) {
ProgressIndicator progressIndicator = new ProgressIndicator();
Button btn = new Button("Go");
VBox root = new VBox(10, btn, progressIndicator);
btn.setOnAction((ActionEvent event) -> {
Task<LineChart> task = new Task<LineChart>() {
@Override
protected LineChart call() throws Exception {
for (int i = 0; i < 10; i++) {
try {
// do some work
Thread.sleep(500);
} catch (InterruptedException ex) {
}
updateProgress(10 * i, 100);
}
updateProgress(100, 100);
return new LineChart(new NumberAxis(), new NumberAxis());
}
};
progressIndicator.progressProperty().bind(task.progressProperty());
task.setOnSucceeded(evt -> {
// handle successful completion of task on application thread
root.getChildren().set(root.getChildren().indexOf(progressIndicator), task.getValue());
});
new Thread(task).start();
});
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}