Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

putting "On Change" listener on jFormattedTextField

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?

like image 597
Ariyan Avatar asked Sep 01 '11 11:09

Ariyan


People also ask

How to use change listener in Java?

In short, to use a simple ChangeListener one should follow these steps: Create a new ChangeListener instance. Override the stateChanged method to customize the handling of specific events. Use specific functions of components to get better undemanding of the event that occurred.


2 Answers

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.

like image 96
kleopatra Avatar answered Oct 13 '22 17:10

kleopatra


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.

like image 22
AngerClown Avatar answered Oct 13 '22 16:10

AngerClown