问题描述
我在阅读课程任务
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
And I notice that updateProgress is protected and workdone/totalwork are both defined as public final ReadOnlyDoubleProperty.
是否有更新/调用 updateProgress的方法/解决方法/编辑这些值( workdone / totalwork
推荐答案
即使 updateProgress(...)
已公开,您必须将任务
的引用传递到您的 DoSomething
类,这会创建一些非常丑的耦合。如果你的任务
实现和你的 DoSomething
类之间有耦合的水平,你可以定义long ,在 Task
子类本身中耗时的方法,并摆脱其他类:
Even if updateProgress(...)
were public, you'd have to pass a reference to the Task
to your DoSomething
class, which creates some really ugly coupling. If you have that level of coupling between your Task
implementation and your DoSomething
class, you may as well just define the long, time consuming method in the Task
subclass itself, and get rid of the other class:
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 ..)
更改时:
To preserve your decoupling, just define a DoubleProperty
representing the progress in DoSomething
, and observe it from the Task
, calling updateProgress(...)
when it changes:
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();
}
}
}
这篇关于调用任务的updateProgress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!