Related to my previous question: Call repaint from another class in Java?
I’m new to Java and I’ve had a look at some tutorials on SwingWorker. Yet, I’m unsure how to implement it with the example code I gave in the previous question.
Can anyone please explain how to use SwingWorker with regards to my code snippet and/or point me towards a decent tutorial? I have looked but I’m not sure I understand yet.
Generally, SwingWorker is used to perform long-running tasks in Swing.
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up, so one of the things which were done is to use
SwingUtilities.invokeLaterandinvokeAndWaitwhich keeps the GUI responsive by which prioritizing the other AWT events before running the desired task (in the form of aRunnable).However, the problem with
SwingUtilitiesis that it didn’t allow returning data from the the executedRunnableto the original method. This is whatSwingWorkerwas designed to address.The Java Tutorial has a section on SwingWorker.
Here’s an example where a
SwingWorkeris used to execute a time-consuming task on a separate thread, and displays a message box a second later with the answer.First off, a class extending
SwingWorkerwill be made:The return type of the
doInBackgroundandgetmethods are specified as the first type of theSwingWorker, and the second type is the type used to return for thepublishandprocessmethods, which are not used in this example.Then, in order to invoke the
SwingWorker, theexecutemethod is called. In this example, we’ll hook anActionListenerto aJButtonto execute theAnswerWorker:The above button can be added to a
JFrame, and clicked on to get a message box a second later. The following can be used to initialize the GUI for a Swing application:Once the application is run, there will be two buttons. One labeled “Answer!” and another “Nothing”. When one clicks on the “Answer!” button, nothing will happen at first, but clicking on the “Nothing” button will work and demonstrate that the GUI is responsive.
And, one second later, the result of the
AnswerWorkerwill appear in the message box.