Home > Software design >  Prevent User From Entering Characters After a Suffix in a Text Field in SWT
Prevent User From Entering Characters After a Suffix in a Text Field in SWT

Time:12-02

I want the user to only write before a suffix. How can I do that in SWT ?

Something like:

public class Test {

    public static void main(String[] args) {
        final String SUFFIX = "end";
        Display display = new Display();
        Shell shell = new Shell(display);

        final Text text = new Text(shell, SWT.BORDER);
        text.setText(SUFFIX);
        text.addVerifyListener(new VerifyListener() {

            @Override
            public void verifyText(VerifyEvent e) {
                // if e.text is after SUFFIX
                // e.doit = false;

            }
        });
    }
}

CodePudding user response:

Something like this:

   text.addVerifyListener(event -> {
      // Get the result text of the edit

      StringBuilder buff = new StringBuilder(text.getText());

      String newText = event.text != null ? event.text : "";

      buff.replace(event.start, event.end, newText);

      // Allow if result still ends with suffix

      event.doit = buff.toString().endsWith(SUFFIX);
    });
  • Related