質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top