How to focus on an element in GWT?

I have this class for an input text box:

    class InputTextBox extends FlowPanel { 
      public InputTextBox(String labelText) { 
        super(); 
        Label label = new Label(labelText); 
        TextBox input = new TextBox(); 
        this.add(label); 
        this.add(input); 
        this.addStyleName("myBox"); 
      }


    }

How to set focus on this text field, so when onmoduleload is called the cursor, appears in the text field? Adding a member function seems to cause a lot of errors.

      public void setFocus(boolean b) {
        this.setFocus(b);

      } 
+5
source share
3 answers

You must add this block to the constructor or onLoad method:

Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
    //call setFocus method here:
    input.setFocus(true);
}});
+3
source

Create a property field for the TextBox and in the setFocus method call textBox.setFocus (true) or as you call it the TextBox property.

+2
source

Change your code like this

class InputTextBox extends FlowPanel {
    private Label label;
    private TextBox textBox;

    public InputTextBox(String labelText) { 
        super(); 
        label = new Label(labelText); 
        textBox = new TextBox(); 
        this.add(label); 
        this.add(input); 
        this.addStyleName("myBox"); 
    }

    public void setFocus(boolean focus) {
        textBox.setFocus(focus);
    }

    public String getText() {
        return textBox.getText();
    }
}

Use it like that

private InputTextBox newUser = new InputTextBox("Username");
newUser.setFocus(true); // Set focus
String value = newUser.getText(); // get text
0
source

All Articles