Java Swing应用程序:如何从GUI线程获取数据到另一个线程? [英] Java Swing application: how to get data from the GUI thread to another thread?

查看:557
本文介绍了Java Swing应用程序:如何从GUI线程获取数据到另一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我使用Swing GUI的Java应用程序中,我想实现以下。

In my Java application with a Swing GUI, I would like to achieve the following.

有一个非GUI线程正在运行,执行一些工作。有一点,这个线程需要用户输入,然后才能继续。然后,我想对GUI进行一些更改,等待特定的GUI操作(例如用户按下OK按钮),将输入的数据从GUI获取到非GUI线程,然后继续进行计算。

There is a non-GUI thread running, performing some work. At one point, this thread needs input from the user before it can continue. Then, I would like to make some changes to the GUI, await a specific GUI action (like the user pressing the OK button), get the entered data from the GUI to the non-GUI thread, and let it continue with the computation.

环顾四周,我发现了很多关于如何从另一个线程上的Swing GUI线程启动(长时间运行)任务的执行的信息,我的问题。

Looking around, I have found a lot of information about how to initiate the execution of a (long running) task from the Swing GUI thread on another thread, but nothing on my problem.

SwingUtilites.invokeAndWait 听起来像它的工作,但首先,它需要一个 Runnable 参数而不是 Callable ,因此没有直接的方法返回结果,其次,它不能解决等待的问题某个GUI事件。

SwingUtilites.invokeAndWait sounds like it does the job, but first, it takes a Runnable argument instead of a Callable, so there is no straightforward way to return a result, and second, it does not solve the problem of waiting for a certain GUI event.

我意识到我可以使用eg a CountDownLatch ,但对我来说,这个问题似乎足够频繁,有一个标准的解决方案。

I realize I could make up my own solution using e.g. a CountDownLatch, but to me, the problem seems frequent enough for there to be a standard solution.

所以,我的问题是:这真的是一个常见的问题,如果是,标准库/库中有解决方案吗?如果没有标准的解决方案,你会如何解决呢?如果这个问题不经常发生,为什么不?

So, my questions are: Is this really a frequent problem, and if yes, is there a solution in the standard library / libraries? If there is no standard solution, how would you solve it? If this problem doesn't occur often, why not?

推荐答案

启动GUI更改很容易,

Kicking off the GUI changes is easy, so I assume you're only asking about getting data back to the worker thread.

首先,创建一个阻止队列。让工作线程在队列上调用 take(),它将被阻塞。在GUI空间中,一旦用户输入有效的输入,用 offer()将其放在队列中,并且工作线程将接收数据并继续。

First, create a Blocking Queue. Have the worker thread call take() on the queue, and it will block. In GUI space, once the user enters valid input, put it on the queue with offer() and the worker thread will receive the data and can continue.

这篇关于Java Swing应用程序:如何从GUI线程获取数据到另一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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