What is the correct way to get a thread to return a value?

I am new to Java threads, and after testing to see how they work, I cannot figure out how to get them to do the calculations and return the result the way I want.

For example, in my current program, I want my thread to query the database by calling a method that returns data in a Vector when the JButton button is pressed. Then, with this vector object, I want to add each index (array) as a string in a JTable .

What would be the right way to achieve this? I know that I could use setter on my JTable in the calling class, but I'm sure there should be a more β€œcorrect” way.

+4
source share
2 answers

Yes, use SwingWorker . This mechanism is designed for situations where you need to perform a multi-year task in the background thread and provide updates to the user interface either upon completion or during processing. Since Swing is single-threaded, this allows the user interface to remain responsive.

+7
source

or the basic workaround on impements Runnable , where the output in the GUI should be wrapped in invokeLater more about Concurrency in the swing

+2
source

All Articles