开发者

putting "On Change" listener on jFormattedTextField

开发者 https://www.devze.com 2023-04-01 15:36 出处:网络
I have a jFormattedTextField in my program and I need to update a jLabel\'s text when jFormattedTextField value has been changed validly.

I have a jFormattedTextField in my program and I need to update a jLabel's text when jFormattedTextField value has been changed validly.

Actually jFormattedTextField gets a number and jLabel displays diffrence between this number and another number.

I currently do this by l开发者_开发问答istenning to "FocusLost" event of jFormatted text.

How can i do this?


register a PropertyChangeListener for the property "value" to the formattedField

    PropertyChangeListener l = new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            String text = evt.getNewValue() != null ? evt.getNewValue().toString() : "";
            label.setText(evt.getNewValue());
        }
    };
    formattedTextField.addPropertyChangeListener("value", l);

Do not use DocumentListener nor FocusListener: the former is notified too often (on every keytyped, before parsing happened) the latter is too brittle.


Probably the easiest way to do this is to use a javax.swing.event.DocumentListener that you attache to the text field. Then, as the user types, the label can be updated.

I don't remember the exact sequence, but the listener's insertUpdate() may be called before the formatted text field is validated. So, you may also need to check for valid numbers in your listener too.

0

精彩评论

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