Search code examples
gwtloadingvisible

GWT, how to make the Loading Label properly?


I got a complicated loop which may take 1 or 2 sec to show the result, so I wanna put a indication to show the users to wait until the program finishes processing, so I make a Label("...loading...") & setVisible to false at the beginning of program & show visible to true before doing the loop then setVisible back to false after the loop finish.

Label loadingLabel=new Label("...loading...");
public void onBind(){
    loadingLabel.setVisible(false);
}
public void onClick(ClickEvent event) {
    loadingLabel.setVisible(true);
    // a lot of loop here
    loadingLabel.setVisible(false);
}

But after running, i didn't see the label visible. So what is the proper way to make Loading Lebel show properly.


Solution

  • First, check that you are adding the Label to the UI, maybe you didn't post that part of your code, but apparently it should be in onBind

    Second, is // a lot of loop here synchronous or asynchronous?. If it is async, you have to hide your label at the end of your callback function.

    Normally I prefer to use the EventBus, and when a large process starts (either it is a synchronous loop, or either a chain of asynchronous calls) y call eventBus.fire(...), then when the last thing finishes, I call eventBus.fire(...) again.

     Label loadingLabel = new Label("");
     RootPanel.get().add(loadingLabel);
     loadingLabel.setVisible(false)
    
     eventBus.addHandler(LoadingEvent.TYPE, new LoadingEvent.Handler() {
       public void onRequestEvent(LoadingEvent ev) {
         if (ev.getMessage() == null) {
            loadingLabel.setVisible(false);
         } else {
            loadingLabel.setText(ev.getMessage());
            loadingLabel.setVisible(true);
         }
       }
     });
    
     // show the label and display a customized message
     eventBus.fire(new LoadingEvent("message"))
    
     // a lot of loop here
    
     // hide the label 
     eventBus.fire(new LoadingEvent(null))
    

    Of course you could have a more sophisticated loading widget with this approach.