Search code examples
javagwtuibinder

adding eventhandler to custom textbox field


Good day

I have a custom TextBox that has a IndicatorTextBox.ui.xml file as well as IndicatorTextBox.java file. Ussually adding an evenhadler to a textbox is simple.

This is in my main .java file

@UiHandler("txtFirstName")
void onTxtFirstNameKeyUp(KeyUpEvent event){ 
validateFields();
}

How would I add the handler if the txtFirstName was the custom textbox with label that I am adding to this page.? So, in other words txtFirstnName is not @UiField TextBox txtFirstName but IndicatorTextField txtFirstName instead.

The IndicatorTextBox.java file looks as follow

import com.google.gwt.core.client.GWT;

public class IndicatorTextField extends Composite implements HasText{

public interface Binder extends UiBinder<Widget, IndicatorTextField> {
}

private static final Binder binder = GWT.create(Binder.class);

public interface Style extends CssResource{
    String textStyling();
    String requiredInputLabel();
    String colorNotValidated();


}

@UiField Style style;
@UiField Label label;
@UiField TextBox textBox;


public IndicatorTextField()
{

    initWidget(binder.createAndBindUi(this));
}

public void setBackgroundValidateTextbox(boolean validated)
{
    if(validated)
    {
        textBox.getElement().addClassName(style.colorNotValidated());
    }
    else
    {
        textBox.getElement().removeClassName(style.colorNotValidated());

    }

}

@Override
public String getText() {

    return label.getText();
}

@Override
public void setText(String text) {
    label.setText(text);

}

Solution

  • Your IndicatorTextField first has to implements the HasKeyUpHandlers interface, catch the KeyUpEvents from the textBox and fire them to its handlers.

    public class IndicatorTextField extends Composite implements HasText, HasKeyUpHandlers {
        ...
    
        @Override
        public HandlerRegistration addKeyUpHandler(KeyUpHandler handler)  {
            return addHandler(handler, KeyUpEvent.getType());
        }
    
        ...
    
        @UiHandler("textBox")
        public void onKeyUp(KeyUpEvent event) {
            DomEvent.fireNativeEvent(event.getNativeEvent(), this);
        }
    
    }
    

    Then in your main java class, if you're creating this IndicatorTextField with uiBinder, then you can just add a UiHandler to it the regular way

    @UiField
    IndicatorTextField myIndicatorTextField;
    
    @UiHandler("myIndicatorTextField)
    public void onKeyUp(KeyUpEvent event) {
        validateFields();
    }
    

    If you're creating by calling the constructor, then call addKeyUpHandler on it

    IndicatorTextField myIndicatorTextField = new IndicatorTextField();
    myIndicatorTextField.addKeyUpHandler(new KeyUpHandler() {
        public void onKeyUp(KeyUpEvent event) {
            validateFields();
        }
    });