【问题标题】:JavaFX: Load data task to combine with progress barJavaFX:加载数据任务以与进度条结合
【发布时间】:2017-05-02 09:03:34
【问题描述】:

对于我的 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 = new TableView&lt;&gt;(model.getSortedCountries());

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

【问题讨论】:

    标签: java multithreading javafx progress-bar javafx-8


    【解决方案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
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2011-12-27
      • 2016-12-10
      相关资源
      最近更新 更多