JavaFX 使用线程和 GUI [英] JavaFX working with threads and GUI

查看:30
本文介绍了JavaFX 使用线程和 GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 JavaFX 和线程时遇到问题.基本上我有两个选择:使用 TasksPlatform.runLater.据我了解 Platform.runLater 应该用于简单/短的任务,而 Task 应该用于较长的任务.但是,我不能使用它们中的任何一个.

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 时,它必须在任务中间弹出一个验证码对话框.在使用 Task 时,它忽略了我显示新对话框的请求......它不允许我创建一个新阶段.

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 所说,你必须使用 TaskService 来处理你需要做的事情在背景中.并且 Platform.runLater 从后台线程在 JavaFX Application 线程中做事情.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆