Home > Software engineering >  SWT Text allow to type only digits
SWT Text allow to type only digits

Time:11-05

I want to allow in a SWT Text to type in only numbers. I already know that I can do this with How to set a Mask to a SWT Text to only allow Decimals.

However the behavior there is not exactly what I want.

If I type in a non digit character it briefly appears in the Text field and than disappears. If I quickly type '123a' it will remove the whole '123a'.

What I want is to prevent the non digit char to appear at all in the Text. Is this possible ?

CodePudding user response:

You could use a key down listener and stop the event for non-digit characters.

text.addListener(SWT.KeyDown, event -> event.doit = Character.isDigit(event.character));

However that very simplistic code means that editing characters such as backspace and arrow keys will also be blocked. So you will need to check the event.keyCode for values to want to allow.

So maybe something like:

text.addListener(SWT.KeyDown, event -> 
            event.doit = event.keyCode == SWT.BS || event.keyCode == SWT.DEL ||
            event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT ||
            Character.isDigit(event.character));

CodePudding user response:

The VerifyListener that intercepts the user input and has a text field that contains the entered text or is empty if some text was deleted.

Usually the text field will just contain the single char triggered by the current key stroke. When pasting text, however, the field contains the entire clipboard text.

The following snippet would prevent any text being inserted that contains non-digit chars.

Text text = new Text(shell, SWT.BORDER);
text.addVerifyListener(event -> {
  if (event.text contains a non-digit char) {
    event.doit = false;
  }
});

I didn't notice that unwanted characters 'slipped through' with this code.

Technically, you could event modify event.text to remove unwanted chars from the text. The event.text field as it is left by the listener will be applied.

From a usability point of view, the entire approach is questionable. Such a listener prevents users from pasting potentially invalid text, cleaning it up and then continue entering other data.

I'd suggest to show a validation error message in a suitable place near the digit-only input field and prevent the user from finishing data entry until the error is resolved (e.g. disable the OK/Save button in a dialog).

If you're already using JFace, you may want to take a look at the dialog validation classes: How to validate a Text with Jface Dialog?

  • Related