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

佐手、 提交于 2019-12-08 11:21:02

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/1378978/using-the-netbeans-gui-editor-how-can-i-create-a-jtextfield-or-jformattedtext-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!