我在看类任务的文档
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是受保护的,工作完成/汇总工作都被定义为公共最终ReadOnlyDoubleProperty。
是否有一种方法/解决方法可以更新/调用updateProgress或从类DoSomething中的方法: VeryLongAndTimeConsumingMethod(int )编辑这些值(工作完成/总计工作)?
发布于 2014-05-16 18:27:48
即使updateProgress(...)是公共的,您也必须将对Task的引用传递给您的DoSomething类,这会创建一些非常难看的耦合。如果在Task实现和DoSomething类之间存在这种级别的耦合,那么最好在Task子类本身中定义长的、耗时的方法,并去掉另一个类:
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(...);
}
};为了保持您的解耦,只需定义一个表示DoSomething进度的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();
}
}
}https://stackoverflow.com/questions/23701639
复制相似问题