Instant value change handler on a GWT textbox

前端 未结 6 1645
清酒与你
清酒与你 2020-12-08 07:25

I would like to update a text field instantly when typing in a GWT TextBox. My problem is that ValueChangeEvent and ChangeEvent handlers only fire when the TextBox loses foc

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 08:19

    As a general solution, what works for me (thx to gal-bracha comment):

    Generally, GWT does not have classes to handle input event (described here and here). So we need to implement it by ourselves:

    Handler class:

    import com.google.gwt.event.shared.EventHandler;
    
    public interface InputHandler extends EventHandler {
    
      void onInput(InputEvent event);
    
    }
    

    Event class:

    import com.google.gwt.event.dom.client.DomEvent;
    
    public class InputEvent extends DomEvent {
    
        private static final Type TYPE = new Type("input", new InputEvent());
    
        public static Type getType() {
            return TYPE;
        }
    
        protected InputEvent() {
        }
    
        @Override
        public final Type getAssociatedType() {
            return TYPE;
        }
    
        @Override
        protected void dispatch(InputHandler handler) {
            handler.onInput(this);
        }
    
    }
    

    Usage:

    box.addDomHandler(new InputHandler() {
    
        @Override
        public void onInput(InputEvent event) {
            text.setText(box.getText());
        }
    },InputEvent.getType());
    

    It works on every TextBox value change including pasting using context menu. It does not react on arrows, ctrl, shift etc...

提交回复
热议问题