Java Reference
In-Depth Information
How it works...
The code in this recipe demonstrates an example of how to use the
ProgressBar
control to
provide gradual feedback on a long-running process. The control works simply. It only requires
the property
progress:Number
to be provided. This is a ratio, between
0.0
and
1.0
, of the
completed activity. The control uses that value to draw the progress bar accordingly.
In the recipe, in order to continually update the progress bar, we bind the
progress
property to the convenience function
ProgressBar.computeProgress(total:Number,
current:Number)
to calculate the progress ratio with the following code segment:
def prog = ProgressBar {
progress: bind ProgressBar.computeProgress(total, counter)
...
}
In this recipe, the long-running process is simulated using an instance of
Timeline
named
timer
. In the code, the
Timeline
instance includes a KeyFrame which restarts repeatedly
every
100ms
due to
repeateCount=Timeline.INDEFINITE
. At the end of each
100ms
,
the KeyFrame executes the function attached to the
action
property. In our example, that
function basically increments the variable
counter
by one if it is less than or equal to the
variable
total
. Otherwise, it stops the timeline. With every increment of
counter
, it causes
the
ProgressBar
instance to update itself because it is bound to the variable
counter
through the
progress
property (see previous code snippet).
There's more...
As mentioned earlier in the recipe, JavaFX also offers the
ProgressIndicator
control
as another class, which can be used to provide users with feedback of progress during a
long-running process. The
ProgressIndicator
operates in the exact same way as the
ProgressBar
and exposes the
progress:Number
property as a way to indicate the ratio
of completion.
ProgressIndicator
, however, is rendered as a circular dial when displaying
progress.
ProgressIndicator
class is suitable for cramped areas where the bar may take
too much screen real estate. You can see an example of the progress indicator in
ch04/
source-code/src/controls/ProgressIndicatorDemo.fx
. It is the same code as
presented above; however, it uses a
ProgressIndicator
instead of a
ProgressBar
, as
shown in the next screenshot.