INFOSYS INFOSYS - 1 month ago 10
Java Question

How to update Progress Bar using double Binding in JavaFX

I have a List of Tasks that update a Common Progressbar, but in my case the bar updates for each task separately, i want to be able to update the progress bar based on the average progress of the tasks, i have tried Double Binding but but it is not working .

Refered Post

Here is what i have Tried

double p = 0.0;
for (final Task t : tasks) {
threadPool.submit(t);

DoubleBinding totalProgress = Bindings.createDoubleBinding(new Callable<Double>() {
@Override
public Double call() {
p = (p+t.getProgress()) / tasks.size();
System.out.println("P"+p + "Progress"+t.getProgress());
return p;
}
});
bar.progressProperty().bind(totalProgress);
//bar.progressProperty().bind(t.progressProperty());
t.setOnSucceeded(handler);

}
threadPool.shutdown();

Answer

Do it the same way as in the example you linked:

Observable[] progressProps = new Observable[tasks.size()];

for (int i = 0 ; i < tasks.size(); i++) {
    progressProps[i]=tasks.get(i).progressProperty();
}

DoubleBinding totalProgress = Bindings.createDoubleBinding(new Callable<Double>() {
    @Override
    public Double call() {
        double total = 0 ;
        for (Task task : tasks) {
            total = total + task.getProgress();
        }
        return total / tasks.size();
    }
}, progressProps);
bar.progressProperty().bind(totalProgress);


for (final Task t : tasks) {
    threadPool.submit(t);
    t.setOnSucceeded(handler);
}