Amit
Amit

Reputation: 34735

Java - Difference between SwingWorker and SwingUtilities.invokeLater()

SwingWorker is used for the following purposes:

SwingUtilities.invokeLater() can perform the above tasks as follows:


I am asking this question because the problem specified in question Java - SwingWorker - Can we call one SwingWorker from other SwingWorker instead of EDT can be solved by SwingUtilities.invokeLater() but can't be solved with SwingWorker

Upvotes: 11

Views: 9015

Answers (2)

Java42
Java42

Reputation: 7706

An important feature of the 1.6+ SwingWorker class is the EDT(Event Dispatch Thread) difference between doInBackground() and done(). You should think of doInBackground() as doWorkOutsideEDT() and done() as doWorkInsideEDT(). Run this instructional example to see the different.

    System.out.println("TID=" + Thread.currentThread().getId() + " (main)");
    final SwingWorker<String, String> x = new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            final long tid = Thread.currentThread().getId();
            System.out.println("");
            System.out.println("TID=" + tid + " doInBackground() isEventDispatchThread=" + SwingUtilities.isEventDispatchThread());
            System.out.println("Long running code goes here.");
            return "";
        }

        @Override
        protected void done() {
            final long tid = Thread.currentThread().getId();
            System.out.println("");
            System.out.println("TID=" + tid + "          done() isEventDispatchThread=" + SwingUtilities.isEventDispatchThread());
            System.out.println("GUI updates/changes go here.");
        }
    };
    x.execute();
    x.get();

Output:

TID=1 (main)

TID=9 doInBackground() isEventDispatchThread=false
Long running code goes here.

TID=16          done() isEventDispatchThread=true
GUI updates/changes go here.

Upvotes: 1

Kathy Van Stone
Kathy Van Stone

Reputation: 26271

SwingWorker is a helper class -- it is not that you need to use it, but using it is much simpler and clearer than doing the same work by hand. (It also makes checking progress easier.) Note that it was added version 6 -- before then some people used a simpler class defined in the Swing Tutorial or did step similar to the ones you noted.

Upvotes: 7

Related Questions