java - Javafx 如何实现一个忙和等待的对话例程
问题描述
我有一个问题,比如在执行进程时在 JavaFX 不确定进度条上暴露的问题,但我使用javafx 对话框警报以便使用如下代码在进度条内显示一个对话框:
Alert busyWaitAlert = new Alert(
Alert.AlertType.INFORMATION);
busyWaitAlert.setContentText("Operation in progress");
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.FINISH);
busyWaitAlert.getButtonTypes().setAll(cancelButton);
busyWaitAlert.setTitle("Running Operation");
busyWaitAlert.setHeaderText("Please wait... ");
ProgressBar progressBar = new ProgressBar();
busyWaitAlert.setGraphic(progressBar);
progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS);
Task<Boolean> task;
task = new Task<Boolean>() {
@Override
public Boolean call() throws Exception {
Collections.sort(LnkListImportedToDb, new importDataToDb.DataItemImportedToDbTimeCmp1());
return true;
}
};
task.setOnSucceeded((e) -> {
busyWaitAlert.close();
});
progressBar.progressProperty().bind(task.progressProperty());
busyWaitAlert.contentTextProperty().bind(task.messageProperty());
new Thread(task).start();
问题是在一个任务中,我调用了一个 Collection.Sort,我不知道它的持续时间,并且我不能在“任务调用”方法中执行 updateMessage,没有这个警报对话框冻结。我认为通过在第一个任务的调用中插入另一个管理 Collection.sort 的任务来解决问题,有更好的解决方案吗?
解决方案
的目的Task
,或更一般地说Worker
,是在后台线程上运行一个长时间运行的进程,同时能够更新用户的进度。该类Task
为您提供了许多允许与 JavaFX 应用程序线程进行安全通信的方法,例如updateProgress
、updateMessage
和setOnSucceeded
. 但是,您不需要 使用这些功能来使用 a Task
;并且不使用这些功能不会Task
以任何方式损害功能。
例如,你可以有一个Task
看起来像这样的非常简单的东西:
public class TaskImpl<E> extends Task<Void> {
private final List<E> list;
public TaskImpl(List<E> list) { this.list = list; }
@Override protected Void call() throws Exception {
list.sort(null);
return null;
}
}
在这里,代码没有利用 ,Task
而只是用于List
在后台线程上对 a 进行排序。外部代码仍然可以观察到Task
没有不良影响。例如,您Alert
的 不会冻结,因为message
和progress
属性没有被更新。
但是,如果您不打算使用 a 的功能Task
,您也可以只使用普通的旧的Runnable
or Callable
。以上在功能上等价于:
() -> list.sort(null);
Runnable
和Task
(实现)有Runnable
一些共同点:没有一个人会为您在单独的线程上运行自己。您实际上必须将工作传递给另一个线程。您可以通过Thread
直接创建一个或更好的选择,使用包Executor
中提供的框架来做到这一点java.util.concurrent
。
尽管如此,我不确定我是否理解您遇到的问题。由于您不知道调用List.sort
将占用Task
'progress
属性多长时间,因此应该简单地保持不确定。如果您想显示一条消息,您可以执行以下操作:
@Override protected Void call() {
updateMessage("Sorting...");
list.sort(null);
updateMessage("Sorting complete.");
updateProgress(1, 1); // jumps progress from indeterminate to 100%
return null;
}
然后将适当的控件绑定到适当的属性,将控件添加到Alert
,并显示Alert
. 这是有关如何执行此操作的完整工作示例:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main extends Application {
private List<Integer> integerList;
@Override
public void init() {
/*
* If there is at least one parameter attempt to parse the
* first one as an Integer. This value will be used as the
* size of the randomly generated "integerList".
*
* If there are no parameters then default to 10 million.
*/
List<String> params = getParameters().getRaw();
if (!params.isEmpty()) {
generateRandomList(Integer.parseInt(params.get(0)));
} else {
generateRandomList(10_000_000);
}
}
private void generateRandomList(int size) {
System.out.printf("Generating random list of %,d integers...%n", size);
Random r = new Random();
integerList = Stream.generate(() -> r.nextInt(size))
.limit(size)
.collect(Collectors.toList());
System.out.println("List generated.");
}
@Override
public void start(Stage primaryStage) {
System.out.println("Building scene graph...");
ListView<Integer> listView = new ListView<>();
listView.setPrefWidth(500);
listView.getItems().addAll(integerList);
Button btn = new Button("Sort List");
btn.setOnAction(ae -> {
ae.consume();
btn.setDisable(true);
/*
* Here we create the task and configure it to set items of the listView
* to the result. We do this because we are sorting "integerList" which
* we had *copied* into the ListView. If we sorted the items of the ListView
* then we would be altering the UI from a background thread (big no-no!).
* Therefore we need to re-copy the "integerList" into the ListView upon
* completion of the task.
*/
SortingTask<Integer> task = new SortingTask<>(integerList, null);
task.setOnSucceeded(wse -> listView.getItems().setAll(task.getValue()));
Alert alert = createProgressAlert(primaryStage, task);
executeTask(task);
alert.show();
});
VBox root = new VBox(btn, listView);
root.setSpacing(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(20));
VBox.setVgrow(listView, Priority.ALWAYS);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.setTitle("Progress Alert Example");
primaryStage.setResizable(false);
primaryStage.show();
System.out.println("Primary stage displayed.");
}
// executes task on a separate, daemon thread
private void executeTask(Task<?> task) {
Thread t = new Thread(task, "sorting-thread");
t.setDaemon(true);
t.start();
}
// creates the Alert and necessary controls to observe the task
private Alert createProgressAlert(Stage owner, Task<?> task) {
Alert alert = new Alert(Alert.AlertType.NONE);
alert.initOwner(owner);
alert.titleProperty().bind(task.titleProperty());
alert.contentTextProperty().bind(task.messageProperty());
ProgressIndicator pIndicator = new ProgressIndicator();
pIndicator.progressProperty().bind(task.progressProperty());
alert.setGraphic(pIndicator);
alert.getDialogPane().getButtonTypes().add(ButtonType.OK);
alert.getDialogPane().lookupButton(ButtonType.OK)
.disableProperty().bind(task.runningProperty());
alert.getDialogPane().cursorProperty().bind(
Bindings.when(task.runningProperty())
.then(Cursor.WAIT)
.otherwise(Cursor.DEFAULT)
);
return alert;
}
// The Task implementation
private static class SortingTask<E> extends Task<List<E>> {
private final List<E> list;
private final Comparator<? super E> comparator;
private SortingTask(List<E> list, Comparator<? super E> comparator) {
this.list = Objects.requireNonNull(list);
this.comparator = comparator; // if null then natural order is used by List.sort
updateTitle("Sorting Task");
}
@Override
protected List<E> call() throws Exception {
updateMessage("Sorting list...");
list.sort(comparator);
updateMessage("Sorting complete.");
updateProgress(1, 1);
return list;
}
@Override
protected void running() {
System.out.println("Sorting task is running...");
}
@Override
protected void succeeded() {
System.out.println("Sorting task successful.");
}
}
}
如果您希望自定义随机生成的列表有多大,您可以将整数作为参数传递给该程序。如果传递了多个参数,则忽略第一个参数。如果没有给出参数,则大小默认为 10,000,000(1000 万)。根据您的计算机,您可能希望增加或减少列表的大小,以免Task
完成太快(或花费太长时间)。
推荐阅读
- kubernetes - kube-system 容器不断崩溃
- unity3d - 如何使用上一个动画状态经过时间的值的偏移量开始动画
- javascript - 用于获取消息标头的加载项
- javascript - 上传单张图片
- kubernetes - 为什么 Kubernetes 配置允许 K8 仪表板连接,但不允许通过 Java API?
- python - 从其他列值匹配的 dataframe2 更新 dataframe1 列中的值
- angularjs - 如何将 \n 与字符串一起替换为空格
- python - 如何从 Python 脚本访问位于 HDFS 中的目录?
- powershell - 使用 Mir 参数的 Robocopy Maxage Minage
- javascript - 将 Javascript 变量传递到 HTML 代码中以用作参数