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 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.
精彩评论