How to use the return value of call method of Task class in Javafx

Bind to the Task's value property OR provide a task.setOnSucceeded() event handler and call task.getValue() in the provided event handler.


Example 1 addEventHandler

MyResultObjectType result;
CustomTask task = new CustomTask();
task.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, 
        new EventHandler<WorkerStateEvent>() {
    @Override
    public void handle(WorkerStateEvent t) {
        result = task.getValue();
    }
});

Example 2 setOnSucceeded

MyResultObjectType result;
CustomTask task = new CustomTask();
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
    @Override
    public void handle(WorkerStateEvent t) {
        result = task.getValue();
    }
});

Example 3 addListener

task.valueProperty().addListener(new ChangeListener<Task>() {
    @Override
    public void changed(ObservableValue<? extends mytype> obs, 
                        mytype oldValue, mytype newValue) {
        if (newValue != null) {
            System.out.println("Result = " + newValue);
        }
    }
});

Tags:

Javafx 2