Instant value change handler on a GWT textbox

前端 未结 6 1607
清酒与你
清酒与你 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条回答
  •  时光说笑
    2020-12-08 08:24

    You could catch the ONPASTE event and manually fire a ValueChangeEvent. Something like this:

    public void onModuleLoad() {
        final Label text = new Label();
        final ExtendedTextBox box = new ExtendedTextBox();
        box.addValueChangeHandler(new ValueChangeHandler() {
    
            @Override
            public void onValueChange(ValueChangeEvent event) {
                text.setText(event.getValue());
            }
    
        });
        box.addKeyUpHandler(new KeyUpHandler() {
    
            @Override
            public void onKeyUp(KeyUpEvent event) {
                text.setText(box.getText());
            }
        });
    
        RootPanel.get().add(box);
        RootPanel.get().add(text);
    }
    
    private class ExtendedTextBox extends TextBox {
    
        public ExtendedTextBox() {
            super();
            sinkEvents(Event.ONPASTE);
        }
    
        @Override
        public void onBrowserEvent(Event event) {
            super.onBrowserEvent(event);
            switch (DOM.eventGetType(event)) {
                case Event.ONPASTE:
                    Scheduler.get().scheduleDeferred(new ScheduledCommand() {
    
                        @Override
                        public void execute() {
                            ValueChangeEvent.fire(ExtendedTextBox.this, getText());
                        }
    
                    });
                    break;
            }
        }
    }
    

    Tested on firefox 3.6.1.

提交回复
热议问题