我正在阅读 class Task 的文档
final Task<Void> task = new Task<Void>() {
@Override public Void call() {
for(int i=0;i<datesAndStudies.length;i++){
updateProgress(i,datesAndStudies.length);
DoSomething something = new DoSomething();
something.VeryLongAndTimeConsumingMethod(i);
}
return null;
}
};
我注意到 updateProgress 受到保护,并且 workdone/totalwork 都被定义为 public Final ReadOnlyDoubleProperty。
有没有办法/解决方法来更新/调用updateProgress或从方法中编辑这些值(workdone/totalwork):类DoSomething中的VeryLongAndTimeConsumingMethod(int i) ?
最佳答案
即使 updateProgress(...)
是公共(public)的,您也必须将对 Task
的引用传递给您的 DoSomething
类,这会产生一些非常丑陋的耦合。如果您的 Task
实现和 DoSomething
类之间具有这种程度的耦合,您不妨在 Task
中定义冗长且耗时的方法code> 子类化自身,并删除其他类:
final Task<Void> task = new Task<Void>() {
@Override
public Void call() {
for (int i=0; i<datesAndStudies.length; i++) {
veryLongAndTimeConsumingMethod(i);
}
return null ;
}
private void veryLongAndTimeConsumingMethod(int i) {
// do whatever...
updateProgress(...);
}
};
为了保持解耦,只需定义一个 DoubleProperty
来表示 DoSomething
中的进度,并从 Task
中观察它,调用 updateProgress(...)
当它改变时:
public class DoSomething {
private final ReadOnlyDoubleWrapper progress = new ReadOnlyDoubleWrapper(this, "progress");
public double getProgress() {
return progress.get();
}
public ReadOnlyDoubleProperty progressProperty() {
return progress.getReadOnlyProperty();
}
public void veryLongAndTimeConsumingMethod(int i) {
// ..
progress.set(...);
}
}
然后:
final Task<Void> task = new Task<>() {
@Override
public Void call() {
for (int i=0; i<datesAndStudies.length; i++) {
DoSomething something = new DoSomething();
something.progressProperty().addListener(
(obs, oldProgress, newProgress) -> updateProgress(...));
something.veryLongAndTimeConsumingMethod();
}
}
}
关于java - 调用任务的updateProgress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701639/