SwingWorker in Java
To perform long-running tasks in Swing without blocking the Event Dispatch Thread (EDT), consider utilizing SwingWorker. This article aims to address a specific use case related to a previous question on "Calling repaint from another class in Java."
Understanding SwingWorker
SwingWorker allows you to run tasks asynchronously, keeping the GUI responsive. It handles data exchange between the background task and the EDT.
Implement SwingWorker in Java
Consider the following code snippet, inspired by the previous question:
// **illustrates previous example** import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.SwingWorker; public class SwingWorkerExample { private static void main(String[] args) { // Initialize GUI JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setLayout(new FlowLayout()); // Create and add a button to trigger the SwingWorker JButton button = new JButton("Start Async Task"); panel.add(button); f.add(panel); f.pack(); f.setVisible(true); // SwingWorker to perform the task SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>() { // executed on a background thread: @Override protected Integer doInBackground() throws Exception { // simulate a heavy task: Thread.sleep(3000); // replace with actual code... return 42; // return an integer result... } // executed on the EDT after doInBackground completes: @Override protected void done() { try { // get the result of the SwingWorker: int result = get(); } catch (Exception ex) { ex.printStackTrace(); } } }; // ActionListener for the button: button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // start the SwingWorker when the button is clicked: worker.execute(); } }); } }
Explanation:
The above is the detailed content of How Can SwingWorker Prevent Blocking the Event Dispatch Thread When Performing Long-Running Tasks in Java?. For more information, please follow other related articles on the PHP Chinese website!