问题
I was reading the documentation for the 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;
}
};
And I notice that updateProgress is protected and workdone/totalwork are both defined as public final ReadOnlyDoubleProperty.
Is there a way/workaround to update/call updateProgress or edit those values(workdone/totalwork) from the method: VeryLongAndTimeConsumingMethod(int i) in the class DoSomething ?
回答1:
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(...);
}
};
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(...);
}
}
Then:
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/call-tasks-updateprogress