CasaDelGato
CasaDelGato

Reputation: 645

Setting waitcursor on glasspane doesn't work in Dialog

I have an app that sometimes kicks off a long-running process in a background thread. If it does this from the main app, I set the wait cursor like this:

oldCursor = App.getInstance().getGlassPane().getCursor();
App.getInstance().getGlassPane().setVisible(true);
App.getInstance().getGlassPane().setCursor(waitCursor);

This works, and I turn off the cursor like this:

App.getInstance().getGlassPane().setCursor(oldCursor);
App.getInstance().getGlassPane().setVisible(false);

So, now I sometimes do a long-running task from a JDialog. (it has setModal(true)) Doing this in the JDialog never changes the cursor:

oldCursor = getGlassPane().getCursor();
getGlassPane().setVisible(true);
getGlassPane().setCursor(waitCursor);

So, I tried setting it for the App, and that didn't work either.

Is there some way to get this working?

Upvotes: 2

Views: 636

Answers (1)

dbc
dbc

Reputation: 717

I know this question is super old. However, I had the same question, and it took me a while of searching through old threads on many websites before I was able to find the solution. Posting it here to help me (and maybe others) find it in the future.

For reference, https://www.javaspecialists.eu/archive/Issue065-Wait-Cursor-Wait.html explains why the OP's code doesn't work. Unfortunately, the solutions presented in that article are less than ideal (e.g., set the cursor before the dialog opens, then change back after it closes).

However, since the JDialog is a top-level Swing container, you can call GetRootPane() directly on it to get access to changing the cursor:

getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// long running code here
getRootPane().setCursor(Cursor.getDefaultCursor());

Another improvement is to set the wait cursor in a try block, and to revert the default cursor in the finally, so you're not left with a forever wait cursor if there's an exception:

try {
    getRootPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    // long running code here
} finally {
    getRootPane().setCursor(Cursor.getDefaultCursor());
}

Upvotes: 0

Related Questions