InputVerifiers
By default, when the focus is lost on a JFormattedTextField the rules for COMMIT_OR_REVERT are followed. That is, if the text typed in is legal, the value is updated and the new value is displayed using the display formatter; if the text is not legal, then the text being edited is discarded and the old value is displayed. A JFormattedTextField can also be set to use the rules for COMMIT, under those rules when an invalid string is entered, it is left displayed, but the value is not changed. When this happens the text shown on the screen does not match the value stored in the JFormattedTextField. So it seems the choice is to lose the edit or have a mismatch in values. Neither of these options is desirable. To correct this, all you need to do is to attach an InputVerifier to the JFormattedTextField. An InputVerifier provides the capability to force the control to retain the focus if it has an invalid value. Further, the formatters attached to a JFormattedTextField usually only check the format of the data; an InputVerifier can perform range checks and other validity checks as well.
An InputVerifier is a class that inherits the InputVerifier class. These classes will contain a constructor and must define the body of an abstract method named "verify". This method is called whenever the focus is about to be lost on a control. If verify returns true, this means all is well and the focus can be moved. If verify returns false, then the focus remains on the control. The verify method accepts a JComponent as input (the JFormattedTextField) and then can do whatever manipulations it needs before returning true or false. The example below is a reusable InputVerifier to handle double values.
The data fields define the minimum and maximum permissible values. The constructor and the included mutator methods can set these. Two Color values are also present, one for invalid values, the other for valid values. The verify method first retrieves the text from the JComponent and tries to parse it to a double. If an exception is thrown, then the foreground color is set to INVALID_COLOR and false is returned. If an exception is not thrown, then the value is tested to see if is in a valid range, if it is, the foreground color is set to the VALID_COLOR and true is returned. If the value is out of range then the foreground color is set to INVALID_COLOR and false is returned. (Also see DoubleVerifier.java which you can download here.)
To use this InputVerifier, first create an instance of the verifier, then attach it to the JFormattedTextField using the setInputVerifier method.
JFormattedTextField salaryField = new JFormattedTextField(); DoubleVerifier salaryVerifier = new DoubleVerifier(0,1000000); salaryField.setInputVerifier(salaryVerifier); // attach the verifier


