我正在尝试显示 ProgressIndicator
执行异步后台ListView
项目加载的时间。我想要的行为是:
- 在开始加载
ListView
项目之前,显示ProgressIndicator
一个不确定的进度; - 异步开始加载
ListView
项目; - 项目加载完成后
ListView
,隐藏ProgressIndicator
.
这是我不成功的尝试的一部分:
public class AsyncLoadingExample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
final ListView<String> listView = new ListView<String>();
final ObservableList<String> listItems = FXCollections.observableArrayList();
final ProgressIndicator loadingIndicator = new ProgressIndicator();
final Button button = new Button("Click me to start loading");
primaryStage.setTitle("Async Loading Example");
listView.setPrefSize(200, 250);
listView.setItems(listItems);
loadingIndicator.setVisible(false);
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
// I have hoped it whould start displaying the loading indicator (actually, at the end of this
// method execution (EventHandler.handle(ActionEvent))
loadingIndicator.setVisible(true);
// asynchronously loads the list view items
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000l); // just emulates some loading time
// populates the list view with dummy items
while (listItems.size() < 10) listItems.add("Item " + listItems.size());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
loadingIndicator.setVisible(false); // stop displaying the loading indicator
}
}
});
}
});
VBox root = VBoxBuilder.create()
.children(
StackPaneBuilder.create().children(listView, loadingIndicator).build(),
button
)
.build();
primaryStage.setScene(new Scene(root, 200, 250));
primaryStage.show();
}
}
在此示例中,ListView
项目是异步加载的。但是, ProgressIndicator
并没有出现。仍然在这个例子中,如果我省略所有Platform.runLater(...)
代码,ProgressIndicator
就会显示出来,但是,当然,ListView
项目没有加载。
因此,我怎样才能实现所需的行为?