java.is.for.desktop java.is.for.desktop - 11 days ago 6
Java Question

Swing: How do I run a job from AWT thread, but after a window was layed out?

My complete GUI runs inside the AWT thread, because I start the main window using

SwingUtilities.invokeAndWait(...)
.

Now I have a JDialog which has just to display a
JLabel
, which indicates that a certain job is in progress, and close that dialog after the job was finished.

The problem is: the label is not displayed. That job seems to be started before
JDialog
was fully layed-out.


When I just let the dialog open without waiting for a job and closing, the label is displayed.

The last thing the dialog does in its ctor is
setVisible(true)
.

Things such as
revalidate()
,
repaint()
, ... don't help either.

Even when I start a thread for the monitored job, and wait for it using
someThread.join()
it doesn't help, because the current thread (which is the AWT thread) is blocked by
join
, I guess.

Replacing
JDialog
with
JFrame
doesn't help either.

So, is the concept wrong in general? Or can I manage it to do certain job after it is ensured that a
JDialog
(or
JFrame
) is fully layed-out?


Simplified algorithm of what I'm trying to achieve:


  • Create a subclass of
    JDialog

  • Ensure that it and its contents are fully layed-out

  • Start a process and wait for it to finish (threaded or not, doesn't matter)

  • Close the dialog



I managed to write a reproducible test case:

EDIT Problem from an answer is now addressed:
This use case does display the label, but it fails to close
after the "simulated process", because of dialog's modality.

import java.awt.*;
import javax.swing.*;

public class _DialogTest2 {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
final JLabel jLabel = new JLabel("Please wait...");
@Override
public void run() {
JFrame myFrame = new JFrame("Main frame");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(750, 500);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);

JDialog d = new JDialog(myFrame, "I'm waiting");
d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

d.add(jLabel);
d.setSize(300, 200);
d.setLocationRelativeTo(null);
d.setVisible(true);

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000); // simulate process
jLabel.setText("Done");
} catch (InterruptedException ex) {
}
}
});

d.setVisible(false);
d.dispose();

myFrame.setVisible(false);
myFrame.dispose();
}
});
}
}

Answer

Try this:

package javaapplication3;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Main {

public static void main(String[] args)
        throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        final JLabel jLabel = new JLabel("Please wait...");

        @Override
        public void run() {
            JFrame myFrame = new JFrame("Main frame");
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setSize(750, 500);
            myFrame.setLocationRelativeTo(null);
            myFrame.setVisible(true);

            JDialog d = new JDialog(myFrame, "I'm waiting");

            d.add(jLabel);
            d.setSize(300, 200);
            d.setLocationRelativeTo(null);
            d.setVisible(true);

            new Thread(new Runnable() {

                @Override
                public void run() {

                public void run() {
                    try {
                        Thread.sleep(3000); // simulate process
                        jLabel.setText("Done");   // HERE: should be done on EDT!
                    } catch (InterruptedException ex) {
                    }
                }
            }).start();


        }
    });
}
}

This one works, but it's not correct. I'll explain whats going on.

Your main() method starts out in 'main' thread. All Swing related code should be done on EDT thread. And this is why You are using (correctly) SwingUtilities.invokeAndWait(...). So far so good.

But there should be no long running tasks on EDT. Since Swing is single threaded any long running processes will block the EDT. So your code Thread.wait(...) should never be executed on EDT. And this is my modification. I wrapped the invocation in another thread. So this is idiomatic long running task handling for Swing. I used Thread class for brevity, but I'd really recommend going with SwingWorker thread.

And very important: I'm making one error in preceding example. See the line with "HERE" comment? This is another Swing one-thread rule violation. Code inside the thread is running outside EDT, so it should never touch Swing. So this code is not a correct with Swing one-thread rule. It's not safe from freezing GUI.

How to correct this? Simple. You should wrap your call in another thread and put it on EDT queue. So correct code should look like:

    SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                jLabel.setText("Done");
            }
        });

EDIT: This question is touching a lot Swing related issues. Can't explain them all at once... But here is one more snippet, which does what You want:

public static void main(String[] args)
        throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {

        final JFrame myFrame = new JFrame("Main frame");
        final JLabel jLabel = new JLabel("Please wait...");
        final JDialog d = new JDialog(myFrame, "I'm waiting");

        @Override
        public void run() {
            myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myFrame.setSize(750, 500);
            myFrame.setLocationRelativeTo(null);
            myFrame.setVisible(true);

            d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

            d.add(jLabel);
            d.setSize(300, 200);
            d.setLocationRelativeTo(null);
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(3000); // simulate process
                        System.out.println("After");
                        SwingUtilities.invokeLater(new Runnable() {

                            public void run() {


                                d.setVisible(false);
                                d.dispose();

                                myFrame.setVisible(false);
                                myFrame.dispose();
                            }
                        });
                    } catch (InterruptedException ex) {
                    }
                }
            }).start();
            d.setVisible(true);

        }
    });
}

To sum up:

  • All Swing related code must run on EDT
  • All long running code must not run on EDT
  • Code can be run on EDT using SwingUtilities....
    • invokeAndWait() - as the name says, call is synchronous,
    • invokeLater() - invoke the code 'sometime', but return immediately
  • If you are on EDT and want to invoke code on another thread, than you can:
    • Create a new Thread (pass a Runnable to new Thread or override it's start() method) and start it ,
    • Create a new SwingWorker thread which has some extras.
    • Possibly use any other threading mechanism (for example Executor threads).

The typical GUI scenario involves:

  1. Creating GUI components,
  2. Wiring up property change listeners,
  3. Executing code related to user actions (i.e. running property change listeners),
  4. Running possibly time consuming tasks,
  5. Updating GUI state,

1., 2., 3. and 4. run on EDT. 4. should not. There are many ways to write proper threading code. The most cumbersome is using Thread class which came with early versions of Java. If one does it naively, resources can be wasted (too many threads runnning at once). Also updating GUI is cumbersome. Using SwingWorker is alleviates the problem a little. It's guaranteed to behave properly while starting, running and updating GUI (each has a dedicated method which you can override and be sure it runs on proper thread).