java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SwingWorkerDemo extends JFrame {

    public SwingWorkerDemo() {
        initialize();
    }

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

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

        processButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                LongRunProcess process = new LongRunProcess();
                try {
                    process.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        helloButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hello There");
            }
        });


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

        this.pack();
        this.setSize(new Dimension(300, 80));
    }

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

    class LongRunProcess extends SwingWorker {
        /**
         *
         * @return
         * @throws Exception
         */
        protected Object doInBackground() throws Exception {
            Integer result = new Integer(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;
        }
    }
}