not able to set focus on TextBox in a GWT app

后端 未结 4 1180
别跟我提以往
别跟我提以往 2021-02-02 10:53

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

相关标签:
4条回答
  • 2021-02-02 11:21

    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.

    0 讨论(0)
  • 2021-02-02 11:21

    Why using DefferedCommand, I think it's better to use someWidget.getElement().focus() which is a native Javascript. I'm using it everywhere, I've not seen any problem.

    0 讨论(0)
  • 2021-02-02 11:47

    It would be so easy for GWT to store a 'wantsFocus' in the internal state, and call focus after the widget is attached. We are still waiting after many years for that feature however...

    Still, even after the attach handler is called, setFocus does not always work.

    So in the meantime, our GwtUtil library has used the following code. It is a combination of several other solutions, and has been wrapped in a utility function:

    static public void setFocus(final FocusWidget focusWidget) {
        if (focusWidget.isAttached()) {
            Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
                @Override
                public void execute() {
                    focusWidget.setFocus(true);
                }
            });
        } else {
            focusWidget.addAttachHandler(new AttachEvent.Handler() {
                @Override
                public void onAttachOrDetach(AttachEvent event) {
                    if (event.isAttached()) {
                        Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
                            @Override
                            public void execute() {
                                focusWidget.setFocus(true);
                            }
                        });
                    }
                }
            });
        }
    }
    

    And call it like this:

    setFocus(myTextBox);
    

    It makes sense to use a utility function; If and when GWT finally makes setFocus work, you won't have to change your source code in multiple places.

    0 讨论(0)
  • 2021-02-02 11:48

    If your Widget extends Composite, you can:

    @Override
    protected void onAttach() {
        super.onAttach();
        textBoxUsername.setFocus(true);
    }
    
    0 讨论(0)
提交回复
热议问题