Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm new to Java threads and after testing to see how they work, I can't figure out how to make them do calculations and return the result the way I want.

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

What would be the correct way to accomplish this? I know I could use a setter on my JTable in the calling class but I'm sure there has to be a more "correct" way.

like image 943
Adam Smith Avatar asked Jan 20 '23 06:01

Adam Smith


1 Answers

Yes, use a SwingWorker. This mechanism is designed for situations where you need to have a long running task run in a background thread and provide updates to the UI either when done, or while processing. Since Swing is single-threaded, this allows the UI to remain responsive.

like image 131
mre Avatar answered Feb 01 '23 07:02

mre