线程任务完成后,JavaFX显示对话 [英] JavaFX show dialogue after thread task is completed
问题描述
我需要显示对话窗口
Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
dialog.setScene(scene);
dialog.showAndWait();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
doSomeStuff();
}
});
我试过
Thread t = new Thread(new Runnable() {
@Override
public void run() {
doSomeStuff();
}
});
t.start();
t.join();
Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
dialog.setScene(scene);
dialog.showAndWait();
}
但是这个应用程序在 doSomeStuff()之前没有响应
已完成
but this app is not responsing until doSomeStuff()
is finished
推荐答案
t.join()
是一个阻塞调用,因此它将阻止FX Application线程,直到后台线程完成。这将阻止重新绘制UI或响应用户输入。
t.join()
is a blocking call, so it will block the FX Application thread until the background thread completes. This will prevent the UI from being repainted, or from responding to user input.
执行所需操作的最简单方法是使用 任务
:
The easiest way to do what you want is to use a Task
:
Task<Void> task = new Task<Void>() {
@Override
public Void call() throws Exception {
doSomeStuff();
return null ;
}
};
task.setOnSucceeded(e -> {
Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
dialog.setScene(scene);
dialog.showAndWait();
});
new Thread(task).start();
低级别(即不使用高级API JavaFX提供)方法是安排从后台线程显示FX应用程序线程上的对话框:
A low-level (i.e. without using the high-level API JavaFX provides) approach is to schedule the display of the dialog on the FX Application thread, from the background thread:
Thread t = new Thread(() -> {
doSomeStuff();
Platform.runLater(() -> {
Stage dialog = new Stage();
dialog.initStyle(StageStyle.UTILITY);
Scene scene = new Scene(new Group(new Text(25, 25, "All is done!")));
dialog.setScene(scene);
dialog.showAndWait();
});
});
t.start();
我强烈建议使用第一种方法。
I strongly recommend using the first approach.
这篇关于线程任务完成后,JavaFX显示对话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!