Using SwingWorker in Java
Introduction
Long-running tasks executed on the Event Dispatch Thread can freeze the GUI. This issue can be addressed by using SwingWorker, which supports the execution of such tasks on a separate thread.
How to Use SwingWorker
Example
In this example, a SwingWorker is used to perform a time-consuming task and display a message box with the result one second later:
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class SwingWorkerExample { private static void makeGUI() { final JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new FlowLayout()); class AnswerWorker extends SwingWorker<Integer, Integer> { protected Integer doInBackground() throws Exception { Thread.sleep(1000); return 42; } protected void done() { JOptionPane.showMessageDialog(f, get()); } } JButton b = new JButton("Answer!"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new AnswerWorker().execute(); } }); f.getContentPane().add(b); f.getContentPane().add(new JButton("Nothing")); f.pack(); f.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(SwingWorkerExample::makeGUI); } }
The above is the detailed content of How Can SwingWorker Prevent GUI Freezes in Java?. For more information, please follow other related articles on the PHP Chinese website!