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

StackOverflow https://stackoverflow.com/questions/1378978

Question

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.

Was it helpful?

Solution

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 ;)

OTHER TIPS

This isn't the easiest solution, but it is a very powerful one: try spring rich client, where validation could be reached via:

public class Validation extends DefaultRulesSource {

private Constraint NAME_VALIDATION = all(new Constraint[]{minLength(3), required()});

public void load() {
    addRules(new Rules(Person.class) {

        @Override
        protected void initRules() {
            add("name", NAME_VALIDATION);
        }
    });

...

and the gui form is easily created via:

    TableFormBuilder formBuilder = getFormBuilder();
    formBuilder.add("firstName");
    formBuilder.add("name");
    formBuilder.row();

E.g. look here for validation or here for more infos. I am using this sucessfully in my open source project ...

This way you could create a more general swing component which could be added to the netbeans component palette

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top