Tuesday, January 24, 2012

SwingWorker

Problem: Perform a time-consuming task, likely to freeze the GUI.
Solution: Use the SwingWorker class, part of java 6.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private Document doc;
...
JButton button = new JButton("Load");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        SwingWorker<Document, Void> worker =
            new SwingWorker<Document, Void>() {
                @Override public Document doInBackground() {
                    return load();
                }
                @Override public void done() {
                    try {
                        doc = get();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
        worker.execute();
   }
});