JavaFX - How to bind Task progress property to another property within the call() method


Question

I am trying to figure out how to bind the progress property of a Task to the property of an object being used inside the Task's call function.

Conceptually, I have an object that does a certain amount of work and exposes its progress via DoubleProperties. Since I would like to to do this (long running) task off of the JavaFX main thread, I would like to wrap it in a Task object and be able to show the progress of the underlying object. However it seems like the only way to update the progress in a Task is through the updateProgress() method, which takes concrete numbers instead of Observables. Similarly, the progressProperty is exposed as a ReadOnlyDoubleProperty, so I can't set the property that way, nor override the progressProperty() method to return the property I would like to use to display progress.

More concretely, this is would I would like to do:

final FooBuilder builder = new FooBuilder();
Task<Void> task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {

         //
         // bind to FooBuilders progress property here...but how?
         // Progress of doLongBuildThing is reflected in an exposed
         // DoubleProperty in the FooBuilder class.
         //
         //       

         builder.doLongBuildingThing(); 
         return null;
    }           
};

This seems like such a basic thing that it should be pretty easy, yet I am not seeing a straightforward way to accomplish it. Any help would be appreciated.

TIA.

  • chooks
1
2
6/19/2014 6:21:54 PM

Accepted Answer

builder.progressProperty().addListener((obs, oldProgress, newProgress) -> 
    updateProgress(newProgress, 1.0));

(assuming FooBuilder's progress property ranges from 0 to 1).

3
6/20/2014 2:02:41 AM

Since your already doing the progress stuff in your object just divide by the max work to get a percentage and bind it to the progress indicator's progress directly (a DoubleProperty). Wrap the binding in a Platform.runLater for safety and you're basically doing all the work of setProgress() in task.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon