JavaFX:加载数据任务以与进度条结合

JavaFX: Load data task to combine with progress bar

对于我的 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 绑定到任务的进度 属性:

pi.progressProperty().bind(model.getTask().progressProperty());

现在我需要从演示模型中的任务加载数据,以便我可以将元素添加到 table:table = new TableView<>(model.getSortedCountries());

如何从加载任务访问表示模型中的数据?

TaskonSucceeded 任务成功时调用的处理程序。 value 属性 具有 call 方法返回的实例。

task.setOnSucceeded(event -> {
    ObservableList<Country> countries = (ObservableList<Country>)event.getSource().getValue();
    // do something
});

Task 在其 call 方法中抛出 Exception 时,也会调用 OnFailed 处理程序。您可以在此处处理异常。 (或捕获 call 方法中的所有异常。)

task.setOnFailed(event -> {
    Throwable e = event.getSource().getException();
    if (e instanceof IOException) {
        // handle exception here
    }
});