【问题标题】:JavaFX working with threads and GUIJavaFX 使用线程和 GUI
【发布时间】:2013-05-18 12:25:56
【问题描述】:

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

当我调用Thread 时,它必须在任务中间弹出一个验证码对话框。在使用Task 时,它忽略了我显示新对话框的请求......它不允许我创建一个新阶段。

另一方面,当我使用Platform.runLater 时,它可以让我显示一个对话框,但是,程序的主窗口会冻结,直到显示弹出对话框。

我需要任何解决方案。如果有人知道如何处理此问题或有类似经验并找到解决方案,我期待您的来信!

【问题讨论】:

标签: multithreading user-interface javafx task


【解决方案1】:

正如 puce 所说,对于需要在后台执行的操作,您必须使用 TaskService。和Platform.runLater 从后台线程在JavaFX Application 线程中做事。

您必须同步它们,其中一种方法是使用 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();

【讨论】:

  • 正是我正在寻找的。非常感谢!
【解决方案2】:

如果您想在后台执行某些操作,请使用 JavaFX 应用程序线程中的 WorkerTaskService)。

http://docs.oracle.com/javafx/2/api/javafx/concurrent/package-summary.html

如果您想在 JavaFX 应用程序线程上执行某些操作,请在后台线程中使用 Platform.runLater

http://docs.oracle.com/javafx/2/api/javafx/application/Platform.html#runLater%28java.lang.Runnable%29

【讨论】:

  • 我创建了一个 Worker(任务)。一旦我需要显示一个弹出窗口,我就会调用 Platform.runLater 但是我需要等待响应(它是输入对话框),但是如果我创建新线程(Platform.runLater)它不会等待响应并且 Worker 继续......如何处理它。也许有一种方法可以暂停 Worker 线程等待来自 Platform.runLater 的输入,然后继续...?
【解决方案3】:

现在回答为时已晚,但对于那些有错误的人,这里是解决方案 XD

你可以使用一个线程。

对线程中的runnablerunlater 使用lambda 表达式。

Thread t = new Thread(() -> {
        //Here write all actions that you want execute on background

        Platform.runLater(() -> {
            //Here the action where is finished the actions on background
        });
    });
t.start();

【讨论】:

    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2013-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多