Home > Java > javaTutorial > How Can SwingWorker Prevent Blocking the Event Dispatch Thread When Performing Long-Running Tasks in Java?

How Can SwingWorker Prevent Blocking the Event Dispatch Thread When Performing Long-Running Tasks in Java?

Barbara Streisand
Release: 2024-12-14 16:41:11
Original
340 people have browsed it

How Can SwingWorker Prevent Blocking the Event Dispatch Thread When Performing Long-Running Tasks in Java?

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();
            }
        });
    }
}
Copy after login

Explanation:

  • In this example, the button click triggers the SwingWorker, which executes the long-running task in the background.
  • The GUI remains responsive while the task is running.
  • Once the task completes, the worker invokes the done() method on the EDT, allowing you to access the result.
  • This approach ensures that the GUI is not blocked by the long-running operation.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template