user2486322
user2486322

Reputation: 867

Java SwingWorker does not work in a main method?

I just try following code but the swingworker is not executing. If I put it in an action of a GUI application (in a button click event) it is executing. What is the technical reason for that?

public static void main(String[] args) {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}

Upvotes: 1

Views: 565

Answers (2)

Tamil
Tamil

Reputation: 1203

See Concurrency in Swing: Initial Threads for more details.

It works after adding SwingUtilities.invokeAndWait

public static void main(String[] args) {

        try {
            SwingUtilities.invokeAndWait(new Runnable() {

                @Override
                public void run() {
                    new SwingWorker<Object, Object>() {
                        @Override
                        protected Object doInBackground() throws Exception {
                            System.out.println("do in background.....");
                            return null;
                        }
                    }.execute();

                }
            });
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

Upvotes: 2

Thomas Kl&#228;ger
Thomas Kl&#228;ger

Reputation: 21435

It is a timing issue. If the background task finishes before the main method it will print "do in background......":

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

    Thread.sleep(100L);
}

If however main finishes before the background task had a chance to run, it will print nothing:

public static void main(String[] args) throws Exception {

    new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            Thread.sleep(100L);
            System.out.println("do in background.....");
            return null;
        }
    }.execute();

}

Upvotes: 1

Related Questions