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:
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();
   }
});