Java Reference
In-Depth Information
in two places. It checks the isCancelled() flag at the top of each iteration, and it also checks the isCancelled() flag
in the InterruptedException handler of the Thread.sleep() call. If the task is cancelled, it calls the updateValue() ,
and gets out of the loop and returns quickly. The return value is ignored by the framework. The shouldThrow field is
controlled by the View to communicate to the task that it should throw an exception.
The View nested class of this program creates a simple UI that has a ProgressBar at the top, a set of Labels at the
center that display the various properties of the worker, and three buttons at the bottom. The contents of the Label s
are bound to the various properties of the worker . The disable properties of the buttons are also bound to the state
property of the worker so that only the relevant buttons are enabled at any time. For example, the Start button is
enabled when the program starts but becomes disabled after it is pressed and the task execution begins. Similarly, the
Cancel and Exception buttons are enabled only if the task is running.
When we run the program in Listing 7-9, the GUI in Figure 7-7 is displayed on the screen.
Figure 7-7. The WorkerAndTaskExample program after starting up
Notice that the progress bar is in an indeterminate state. The values of Title, Message, Value, and Exception are
empty. The value of Running is false. The value of State is READY, the values of Total Work and Work Done are -1.0,
and Progress displays -100%. The Start button is enabled, whereas the Cancel and Exception buttons are disabled.
After the Start button is clicked, the task starts to execute and the GUI automatically reflects the values of the
properties as the task progresses. Figure 7-8 is a screenshot of the application at this stage. Notice that the progress
bar is in a determinate state and reflects the progress of the task. The values of Title and Message reflects what is set
to these properties in the implementation of the call() method in the task. The value of Running is true. The value
of State is RUNNING, and the values of Total Work, Work Done, and Progress reflect the current state of the executing
task: 156 of 250 items done. The Value and the Exception fields are empty because neither a value nor an exception is
available from the task. The Start button is disabled now. The Cancel and Exception buttons are enabled, indicating
that we may attempt to cancel the task or force an exception to be thrown from the task at this moment.
 
Search WWH ::




Custom Search