开发者

JtextField with data validation and Beansbinding

I am trying to bind a JTextfield with text validation and then bind it to a pojo model. My target is to allow user to type certain set of allowable characters with specific text length, and set the text in the model using binding. The code snippet is given below.

public class TestValidationBinding {
    private JTextField field;
    private ModelVo modelVo;

    public TestValidationBinding() {
        field = new JTextField();
        modelVo = new ModelVo();
        field.setDocument(new PlainDocument() {
            private static final long serialVersionUID = 1L;

            @Override
            public void insertString(int offs, String str, AttributeSet a)
                    throws BadLocationException {
                // other validation for key typing, check length
                int limit = 15;
                if (str == null) {
                    return;
                }

                if ((getLength() + str.length()) <= limit) {
                    super.insertString(offs, str, a);
                }
            }
        });

        Property srcProperty = BeanProperty.create("text");
        Property tgtProperty = BeanProperty.create("text");
        AutoBinding binding = Bindings
                .createAu开发者_高级运维toBinding(UpdateStrategy.READ_WRITE, field,
                        srcProperty, modelVo, tgtProperty);
        binding.bind();

    }
}

The ModelVO class is:

public class ModelVo {
    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        System.out.println("Text is:" + text);
        this.text = text;
    }
}

I am using AspectJ to fire necessary property changes in the ModalVO class. (followed this link to achieve this:: http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop/#comments ).

Now, my problem is if I do not use binding, the validation is done properly but the text is not set in modal. But if I bind textfield, the text is set in the model properly, but validation does not work. Could anyone provide insight why it is not working when I am using both validation and binding together?


Try to use javax.swing.text.DocumentFilter instead of extendint the PlainDocument.


Try to override replace method instead of insertString if You use binding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜