Domanda

I am using a JFormattedTextField, when i try to delete the value in the field, it automatically restores the previous value. What is the reason for this behaviour and how can i stop it restoring the value?

This is the code for JFormattedtextField.

jFormattedTextField2 = new javax.swing.JFormattedTextField(new DecimalFormat("###,###.##"));
È stato utile?

Soluzione

It happens because JFormattedTextField allows configuring what action should be taken when focus is lost using the setFocusLostBehavior method.

These are the actions.

Description

JFormattedTextField.REVERT - Revert the display to match that of getValue, possibly losing the current edit.

JFormattedTextField.COMMIT - Commits the current value. If the value being edited isn't considered a legal value by the AbstractFormatter that is, a ParseException is thrown, then the value will not change, and then edited value will persist.

JFormattedTextField.COMMIT_OR_REVERT - Similar to COMMIT, but if the value isn't legal, behave like REVERT.

JFormattedTextField.PERSIST - Do nothing, don't obtain a new AbstractFormatter, and don't update the value.

**** The default is JFormattedTextField.COMMIT_OR_REVERT so when you enter an invalid value, it's reverted and you get the previous consistent state**

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top