Typically, SwingWorker is used to perform lengthy tasks in Swing.
Performing lengthy tasks in the event dispatch (EDT) stream can lead to GUI blocking, so one of the things that were done is to use SwingUtilities.invokeLater and invokeAndWait , which supports a graphical interface that prioritizes other AWT events before running the task ( to form a Runnable ).
However, the problem with SwingUtilities is that it did not allow you to return data from a Runnable run to the original method. This is what SwingWorker is for addressing.
The Java tutorial has a SwingWorker section.
Here is an example where a SwingWorker used to perform a time-consuming task in a separate thread and displays a message box in a second with a response.
First of all, the SwingWorker class will be created:
class AnswerWorker extends SwingWorker<Integer, Integer> { protected Integer doInBackground() throws Exception {
The return type of the doInBackground and get methods is specified as the first type of SwingWorker , and the second type is the type returned for publish and process methods that are not used in this example.
Then, to call SwingWorker , the execute method is called. In this example, we will connect an ActionListener to a JButton to execute AnswerWorker :
JButton b = new JButton("Answer!"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new AnswerWorker().execute(); } });
The above button can be added to the JFrame and pressed to get the message box in a second. You can use the following to initialize the GUI for a Swing application:
private void makeGUI() { final JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new FlowLayout()); // include: "class AnswerWorker" code here. // include: "JButton" b code here. f.getContentPane().add(b); f.getContentPane().add(new JButton("Nothing")); f.pack(); f.setVisible(true); }
After launching the application there will be two buttons. One is marked as "Answer!". and other "Nothing." When you click βAnswer!β, Nothing will happen at first, but pressing the βNothingβ button will work and demonstrate that the graphical interface is responsive.
And, after a second, the result of AnswerWorker appears in the message box.