javamultithreadingswingglasspane

Java: "please wait" GlassPane not correctly loaded


I have a java routine that takes several second to be completed. I'd like to load a GlassPane (possibly with a "prease wait" message inside) that prevents the user to modify the UI while that routine is under execution and that is automatically hidden when the routine finishes. To do this, I use the following code:

Thread t = new Thread(new Runnable(){
    @Override
    public void run() {
        /*
         * `getPresentation().getFrame()` are methods that return the 
         * Frame which contains my UI
         */
        getPresentation().getFrame().setGlassPane(myGlassPane);
        getPresentation().getFrame().getGlassPane().setVisible(true);
    }
});
t.start();

//this is the routine that takes several seconds to be executed
runCEM();

//hide the GlassPane
getPresentation().getFrame().getGlassPane().setVisible(false);

I set a specific java.awt.Cursor to myGlassPane. When I run the above code, I can see the new java.awt.Cursor appearing, but not the whole GlassPane with the "please wait" message and so on...

Any idea about what could cause this issue? Are there maybe other better ways to get what I'm looking for instead of using GlassPane and Thread?


Solution

  • Swing is not thread safe, so already, you're violating the single thread rules of Swing, possibly on two accounts. First, the glassPane should be shown and hidden from within the context of the EDT (Event Dispatching Thread).

    Your long running process should be executed off the EDT.

    The simplest solution I can think of is to use a SwingWorker. This provides a number of useful mechanisms which you can use to perform long running or blocking processes in another thread and update the UI safely with.

    Take a look at Concurrency in Swing and Worker Threads and SwingWorker for more details