Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing application: how to get data from the GUI thread to another thread?

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

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.

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 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.

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?

like image 522
sandris Avatar asked Feb 22 '23 09:02

sandris


2 Answers

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

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.

like image 138
Bill Avatar answered Feb 24 '23 02:02

Bill


I think, you can use ExecutorService where you can also track progress of your task through Future interface.

like image 36
JProgrammer Avatar answered Feb 24 '23 01:02

JProgrammer