putting "On Change" listener on jFormattedTextField
Asked Answered
R

2

12

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 listenning to "FocusLost" event of jFormatted text.

How can i do this?

Rebatement answered 1/9, 2011 at 11:45 Comment(0)
L
18

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.

Ladanum answered 1/9, 2011 at 13:35 Comment(1)
Unfortunately this doesn't get called often enough. Seems to work like I'd expect a FocusListener. But the DocumentListener gets called even when simply entering the field.Electronic
C
1

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.

Circumflex answered 1/9, 2011 at 12:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.