not able to set focus on TextBox in a GWT app

sherry picture sherry · May 10, 2011 · Viewed 16k times · Source

This should not be causing me so much pain but it is. It is a very weird problem. In a GWT application, I have two .java files, login.java and application.java. In login.java, I'm creating a user login page where if the username and password is verified the user is logged into the application and application.java takes from here.

Now in application. java's onModuleLoad() this is how i'm starting with a login page.

public void onModuleLoad() {
  Login login = new Login();
  login.textBoxUsername.setFocus(true);
  RootLayoutPanel.get().add(login);}

This works great, except for the tiny problem of not being able to set focus on the username TextBox when the page loads. I have tried evrything I can think of. But the focus just doesn't get set on the TextBox. If anyone can suggest a solution, please do. Your help is greatly appreciated.

Solution: (In case it helps anyone facing the same issue)

final Login login = new Login();
  Scheduler.get().scheduleDeferred(new ScheduledCommand() {
        public void execute () {
            login.textBoxUsername.setFocus(true);
        }
   });

  RootLayoutPanel.get().add(login);

Answer

Peter Knego picture Peter Knego · May 10, 2011

Try using Scheduler.scheduleDeferred():

public void onModuleLoad() {
    Login login = new Login();
    Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
        public void execute () {
            login.textBoxUsername.setFocus(true);
        }
    });
    RootLayoutPanel.get().add(login);       
}

Update: answer updated to use Scheduler.get().scheduleDeferred() instead of DeferredCommand, which is deprecated.