我有两个任务,一个用于更改屏幕不透明度,另一个用于执行复杂计算。我希望计算只在屏幕淡化实际发生变化后才开始,所以我写了以下内容:
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
stage.getScene().getRoot().setOpacity(0.2);
stage.show();
return null;
}
};
Task<Void> task2 = new Task<Void>() {
@Override
protected Void call() throws Exception {
// Complex computation
return null;
}
};
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent paramT) {
// this busy waiting line was added in attempt to force the
// fading before beginning second task
while (stage.getScene().getRoot().getOpacity() != 0.2) {}
stage.show();
Platform.runLater(task2);
}
});
task2.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent paramT) {
stage.getScene().getRoot().setOpacity(1);
stage.show();
}
});
task.run();
但是,有时我会看到计算开始,屏幕在完成之后才会消失。有时它确实有效。所以我认为这里存在一个线程问题。注意:当我处于调试模式并停在每个任务时,它确实每次都有效。在第二个任务开始之前可以做些什么来强制屏幕淡出?
编辑: 根据建议,我将代码更改为以下内容:
Task<Void> task1 = new Task<Void>() {
@Override
protected Void call() throws Exception {
// Long computation
return null;
}
};
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
FadeTransition ft = new FadeTransition(Duration.millis(1), stage.getScene().getRoot());
ft.setFromValue(1.0);
ft.setToValue(0.1);
ft.setCycleCount(1);
//ft.setAutoReverse(true);
ft.play();
ft.setOnFinished(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
new Thread(task1).run();
}
});
return null;
}
};
task1.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent paramT) {
FadeTransition ft1 = new FadeTransition(new Duration(0.1), stage.getScene().getRoot());
ft1.setFromValue(0.1);
ft1.setToValue(1.0);
ft1.setCycleCount(1);
//ft.setAutoReverse(true);
ft1.play();
//stage.show();
}
});
new Thread(task).run();
我仍然看到同样的行为。
答案 0 :(得分:0)
替换
new Thread(task).run();
与
new Thread(task).start();