Java如何使用SwingWorker执行后台任务?

该演示给出了使用SwingWorker该类的示例。目的SwingWorker是实现一个后台线程,您可以使用该线程执行耗时的操作,而不会影响程序GUI的性能。

package org.nhooo.example.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(300, 80));
    }

    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);

                    // 睡眠一段时间以模拟一个漫长的过程
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }

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