对于我的JavaFX应用程序,我想实现一个加载任务,将它与进度条结合起来。
我有一个演示模型,如下所示:
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();
}
}
加载数据的任务:
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;
}
}
这允许我将ProgressIndicator pi
绑定到任务的progress属性:
pi.progressProperty().bind(model.getTask().progressProperty());
现在我需要从演示模型中的任务中加载数据,以便我可以将元素添加到表中:table = new TableView<>(model.getSortedCountries());
如何从加载任务访问演示模型中的数据?
答案 0 :(得分:1)
Task
会调用onSucceeded
处理程序。 value
属性具有call
方法返回的实例。
task.setOnSucceeded(event -> {
ObservableList<Country> countries = (ObservableList<Country>)event.getSource().getValue();
// do something
});
当Task
方法中出现OnFailed
时, Exception
也会调用call
处理程序。你可以在这里处理例外。 (或者在call
方法中捕获所有异常。)
task.setOnFailed(event -> {
Throwable e = event.getSource().getException();
if (e instanceof IOException) {
// handle exception here
}
});