How do I use SwingWorker to perform background tasks?

This demo gives examples of using the SwingWorker class. The purpose of SwingWorker is to implement a background thread that you can use to perform time-consuming operations without affecting the performance of your program’s GUI.

package org.kodejava.swing;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import java.awt.Dimension;
import java.awt.FlowLayout;

public class SwingWorkerDemo extends JFrame {

    public SwingWorkerDemo() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new SwingWorkerDemo().setVisible(true));
    }

    private void initialize() {
        this.setLayout(new FlowLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        JButton processButton = new JButton("Start");
        JButton helloButton = new JButton("Hello");

        processButton.addActionListener(event -> {
            LongRunProcess process = new LongRunProcess();
            try {
                process.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        helloButton.addActionListener(e ->
            JOptionPane.showMessageDialog(null, "Hello There"));

        this.getContentPane().add(processButton);
        this.getContentPane().add(helloButton);

        this.pack();
        this.setSize(new Dimension(500, 500));
    }

    static class LongRunProcess extends SwingWorker<Integer, Integer> {
        protected Integer doInBackground() {
            int result = 0;
            for (int i = 0; i < 10; i++) {
                try {
                    result += i * 10;
                    System.out.println("Result = " + result);

                    // Sleep for a while to simulate a long process
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

        @Override
        protected void done() {
            System.out.println("LongRunProcess.done");
        }
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.