Java Reference
In-Depth Information
Extensions of
Task<V>
must override the protected abstract
call()
method to perform the actual work.
The implementation of the
call()
method may call the protected methods
updateTitle()
,
updateMessage()
,
updateProgress()
, and
updateValue()
to publish its internal state to the JavaFX application thread. The
implementation has total control of what the title and message of the task should be. For the
updateProgress()
call that
takes two longs, the
workDone
and
totalWork
must either both be
-1
, indicating indeterminate progress, or satisfy the
relations
workDone >=0
and
workDone <= totalWork
, resulting in a
progress
value of between
0.0
and
1.0
(
0%
to
100%
).
■
the
updateProgress()
api will throw an exception if
workDone > totalWork
, or if one of them is
<-1
.
however, it allows you to pass in
(0, 0)
, resulting in a progress of
NaN
.
Caution
The two
cancel()
methods can be called from any thread, and will move the task to the
CANCELLED
state if it is not
already in the
SUCCEEDED
or
FAILED
state. If either
cancel()
method is called before the task is run, it will move to the
CANCELLED
state and will never be run. The two
cancel()
methods differ only if the task is in the
RUNNING
state, and
only in their treatment of the running thread. If
cancel(true)
is called, the thread will receive an interrupt. For this
interrupt to have the desired effect of causing the task to finish processing quickly, the implementation of the
call()
method has to be coded in a way that will detect the interrupt and skip any further processing. The no-argument
cancel()
method simply forwards to
cancel(true)
.
Listing 7-9 illustrates the creation of a
Task
, starting it, and observing the properties of the task from a simple GUI
that displays all nine of the properties.
Listing 7-9.
WorkerAndTaskExample.java
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.concurrent.atomic.AtomicBoolean;
public class WorkerAndTaskExample extends Application {
private Model model;
private View view;
public static void main(String[] args) {
launch(args);
}
Search WWH ::
Custom Search