GWT - How to show the wait cursor for long tasks

In case you have a task that takes more than 2 seconds you need to signal to the user that he needs to wait a little longer than usual. This can be done in many ways, here, we are talking about the setting the cursor to a WAIT cursor.

For this reason we have wrote 2 static functions to set the cursor to wait and then to put it back when the long task is over.

public static void showWaitCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "wait");
}

public static void showDefaultCursor() {
    DOM.setStyleAttribute(RootPanel.getBodyElement(), "cursor", "default");
}

Here are the possible types of the HTML cursors, which can be used in different cases:

 


Example of how to use the functions to change HTML cursor for long task:

/**
 * create the long task instance, which in our case extends:
 *   interface Function { execute(); } 
 */
final Task longTask = new Task();

/** shows the wait cursor */
showWaitCursor();

/** launch the long task in a separate thread */
DeferredCommand.addCommand (new Command() {
    @Override
    public void execute () {
        try {
            longTask.execute();
        } finally {
            /* when task finishes (successful, or with failure) set back the default cursor */
            showDefaultCursor();
        }
    }
});

That's pretty much all.

Cheers!

2 comments:

  1. I have utilized the same line of code for converting Normal cursor to hour glass cursor and vice versa.

    Unfortunately, this code is not working for me. Am I missing some other line(s) of code? Please comments.

    Thanks

    ReplyDelete