capint
1/6/2017 - 12:16 PM

Eclipse >> SWT >> Text validator

Eclipse >> SWT >> Text validator

final Text txt = new Text(composite, SWT.MULTI);
txt.addModifyListener(new ModifyListener() {
  ControlDecoration decorator;
  {
    decorator = new ControlDecoration(txt, SWT.CENTER);
    decorator.setDescriptionText("Not a valid number");
    Image image = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR).getImage();
    decorator.setImage(image);
    decorator.hide();
  }
  @Override
  public void modifyText(ModifyEvent event) {
    try {
      String text = ((Text) event.getSource()).getText();
      if (!text.matches("\\d*")) { 
        decorator.show();
        setValid(false);
      }
      else {
        decorator.hide();
        setValid(true);
      }
    } catch (BackingStoreException ex) {
      ex.printStackTrace();
    }
  }
});