Reputation: 679
For my JavaFX application I'd like to implement a load Task, to combine it with a progress bar.
I have a Presentation Model which looks like this:
public class PresentationModel {
private final ObservableList<Country> countries = FXCollections.observableArrayList();
// Wrap the ObservableList in a FilteredList (initially display all data)
private final FilteredList<Country> filteredCountries = new FilteredList<>(countries, c -> true);
// Wrap the FilteredList in a SortedList (because FilteredList is unmodifiable)
private final SortedList<Country> sortedCountries = new SortedList<>(filteredCountries);
private Task<ObservableList<Country>> task = new LoadTask();
public PresentationModel() {
new Thread(task).start();
}
}
And a Task which loads the data:
public class LoadTask extends Task<ObservableList<Country>> {
@Override
protected ObservableList<Country> call() throws Exception {
for (int i = 0; i < 1000; i++) {
updateProgress(i, 1000);
Thread.sleep(5);
}
ObservableList<Country> countries = FXCollections.observableArrayList();
countries.addAll(readFromFile());
return countries;
}
}
This allows me to bind the ProgressIndicator pi
to the progress property of the task:
pi.progressProperty().bind(model.getTask().progressProperty());
Now I need to have the loaded data from the task in the presentation model so that I can add the elements to a table: table = new TableView<>(model.getSortedCountries());
How can I access the data in the presentation model from the load task?
Upvotes: 0
Views: 635
Reputation: 884
Task
has onSucceeded
handler called when the task succeeds. The value
property has the instance returned by call
method.
task.setOnSucceeded(event -> {
ObservableList<Country> countries = (ObservableList<Country>)event.getSource().getValue();
// do something
});
Task
also has OnFailed
handler called when Exception
was thrown in its call
method. You can handle exceptions here. (or catch all exceptions in call
method.)
task.setOnFailed(event -> {
Throwable e = event.getSource().getException();
if (e instanceof IOException) {
// handle exception here
}
});
Upvotes: 1