1
我正在进行基本的Java FX任务练习。它从1到150在一个线程上计数。当前值显示在标签上并更新进度条。JavaFX任务不重新运行一次取消或完成一次
有一个按钮可以启动任务,取消它并查看任务的取消状态。
让我感到困惑的是,为什么在取消线程一次后我不能重新运行任务(如果我让任务完成,也会发生同样的事情)。
我希望能够重新运行任务。然后我需要使它恢复(尽管在弄清楚如何重新运行任务之后不应该那么难)
来源;
public class JavaFX_Task extends Application {
@Override
public void start(Stage primaryStage) {
final Task task;
task = new Task<Void>() {
@Override
protected Void call() throws Exception {
int max = 150;
for (int i = 1; i <= max; i++) {
if (isCancelled()) {
break;
}
updateProgress(i, max);
updateMessage(String.valueOf(i));
Thread.sleep(100);
}
return null;
}
};
ProgressBar progressBar = new ProgressBar();
progressBar.setProgress(0);
progressBar.progressProperty().bind(task.progressProperty());
Label labelCount = new Label();
labelCount.textProperty().bind(task.messageProperty());
final Label labelState = new Label();
Button btnStart = new Button("Start Task");
btnStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
new Thread(task).start();
}
});
Button btnCancel = new Button("Cancel Task");
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
task.cancel();
}
});
Button btnReadTaskState = new Button("Read Task State");
btnReadTaskState.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
labelState.setText(task.getState().toString());
}
});
VBox vBox = new VBox();
vBox.setPadding(new Insets(5, 5, 5, 5));
vBox.setSpacing(5);
vBox.getChildren().addAll(
progressBar,
labelCount,
btnStart,
btnCancel,
btnReadTaskState,
labelState);
StackPane root = new StackPane();
root.getChildren().add(vBox);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
哇,我现在感觉像一个延迟:(... – user3612698
没有必要这样感觉。作为第一个问题,你的比许多:-) – jewelsea