问题描述
使用JavaFX和Threads时遇到问题。基本上我有两个选择:使用任务
或使用Platform.runLater
。据我所知, Platform.runLater
应该用于简单/短期任务,任务
用于较长的任务。但是,我不能使用它们中的任何一个。
I have a problem while working with JavaFX and Threads. Basically I have two options: working with Tasks
or Platform.runLater
. As I understand Platform.runLater
should be used for simple/short tasks, and Task
for the longer ones. However, I cannot use any of them.
当我调用 Thread
时,它必须弹出验证码对话框在任务中间。在使用任务
时,它忽略了我显示新对话框的请求...它不允许我创建一个新阶段。
When I call Thread
, it has to pop up a captcha dialog in a middle of task. While using Task
, it ignores my request to show new dialog... It does not let me to create a new stage.
另一方面,当我使用 Platform.runLater
时,它会让我显示一个对话框,但是,程序的主窗口冻结,直到显示弹出对话框。
On the other hand, when I use Platform.runLater
, it lets me show a dialog, however, the program's main window freezes until the pop up dialog is showed.
我需要任何类型的解决方案。如果有人知道如何处理这个或有类似的经验并找到了解决方案,我期待着您的回复!
I need any kind of solution for this. If anyone knows how to deal with this or had some similar experience and found a solution I am looking forward to hearing from you!
推荐答案
正如puce所说,你必须使用任务
或服务
来完成你需要在后台完成的事情。并且 Platform.runLater
在后台线程的JavaFX应用程序线程中执行操作。
As puce says, you have to use Task
or Service
for the things that you need to do in background. And Platform.runLater
to do things in the JavaFX Application thread from the background thread.
您必须同步它们,其中一种方法是使用类 CountDownLatch
。
You have to synchronize them, and one of the ways to do that is using the class CountDownLatch
.
这是一个例子:
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
//Background work
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override
public void run() {
try{
//FX Stuff done here
}finally{
latch.countDown();
}
}
});
latch.await();
//Keep with the background work
return null;
}
};
}
};
service.start();
这篇关于JavaFX使用线程和GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!