Java Reference
In-Depth Information
Figure 14-11
shows the Background Processes application, which simulates a file
copy window.
Figure 14-11
.
Background processes
How It Works
One of the main pitfalls of GUI development is knowing when and how to delegate
work (
Threads
). You are constantly reminded of thread safety, especially when it
comes to blocking the GUI thread. When using the Java Swing API, the
SwingWork-
er
object must be implemented to defer non-GUI work off of the event dispatch thread
(EDT). Similar patterns and principles still apply in the world of JavaFX.
You begin by creating not one but two progress controls to show the user the work
being done. One is a progress bar and the other is a progress indicator. The progress in-
dicator shows a percentage below the indicator icon. The following code snippet shows
the initial creation of progress controls:
final ProgressBar progressBar = new ProgressBar(0);
final ProgressIndicator progressIndicator = new
ProgressIndicator(0);
Next, you create a worker thread via the
createWorker()
method. The
cre-
ateWorker()
convenience method will instantiate and return a
javafx.concurrent.Task
object, which is similar to the Java Swing's
SwingWorker
class. Unlike the
SwingWorker
class, the
Task
object is greatly
simplified and easier to use. If you compare the last recipe you will notice that none of
the GUI controls is passed into the
Task
. The clever JavaFX team has created observ-
able properties that allow you to bind against. This fosters a more event-driven ap-