Skip to content
Advertisement

Using the NetBeans GUI editor, how can I create a JTextField or JFormattedText field that must be validated against a regular expression?

I have a regular expression (d{4}w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}) that I need to validate the input of a text field against when the user clicks the OK button or moves the cursor to another field. That I know how to do, writing the code. However, I’m interested in if it’s possible to have the NetBeans GUI editor do some of the work for me, especially since I’m moving away from Eclipse and towards NetBeans as my IDE of choice, and I would like to take full advantage of the tools it provides.

Advertisement

Answer

Open the Properties of your JTextField, in the Properties tab look for inputVerifier. Open it

Now you’ll be asked to introduce the InputVerifier code.

ftf2.setInputVerifier(new InputVerifier() {
  public boolean verifyText(String textToVerify) {
     Pattern p = Pattern.compile("your regexp");
     Matcher m = p.matcher(textToVerify);
        if (m.matches()) {
        setComponentValue(textToVerify);
        return true;
    }
    else {
        return false;
    }

  }
});

I haven’t compiled this code, so could contain errors. But I think you get the idea 😉

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement