Java Reference
In-Depth Information
proach to handling work (tasks). When creating an instance of a Task object you im-
plement the call() method to perform work in the background. During the work be-
ing done, you may wish to queue up intermediate results such as progress or text info.
For this, you can call the updateProgress() and updateMessage() methods.
These methods will update information in a threadsafe manner so that the observer of
the progress properties will be able to update the GUI safely without blocking the GUI
thread. The following code snippet demonstrates the ability to queue up messages and
progress:
// queue up status
updateMessage(status);
updateProgress(i + 1, numFiles);
After creating a worker Task , you unbind any old tasks bound to the progress con-
trols. Once the progress controls are unbound, you then bind the progress controls to
the newly created Task object called copyWorker . Shown here is the code used to
rebind a new Task object to the progress UI controls:
// wire up progress bar
progressBar.progressProperty().unbind();
progressBar.progressProperty().bind(copyWorker.progressProperty());
progressIndicator.progressProperty().unbind();
progressIndicator.progressProperty().bind(copyWorker.progressProperty());
Next, you implement a ChangeListener to append the queued results into the
TextArea control. Another remarkable thing about JavaFX properties is that you can
attach many listeners similar to Java Swing components. Finally the worker and con-
trols are all wired up to spawn a thread to go off in the background. The following code
line shows how to launch a Task worker object:
new Thread(copyWorker).start();
Lastly, the Cancel button will simply call the Task object's cancel() method to
kill the process. Once the task is cancelled the progress controls are reset. Once a work-
er Task is cancelled it cannot be reused. When pressed, the Start button recreates a
new Task . If you want a more robust solution, you should look at the
javafx.concurrent.Service class. The following code line will cancel a
Task worker object:
Search WWH ::




Custom Search