I use the following code, to apply a MaskFormatter on my JFormattedTextField
in order to make it accept IBANs (2 letters followed by 20 digits):
MaskFormatter formatter = new MaskFormatter("UU## #### #### #### #### ##");
formatter.setPlaceholderCharacter('_');
jFormattedTextField.setFormatterFactory(new DefaultFormatterFactory(formatter));
Whenever there's an empty space in that textfield, the placeholder character ('_') holds that place as intended. But once you focus a different textfield, the field will check if the String inside is valid, and reset it otherwise. However, I don't want it to change if it looks like this for example:
AA00 11_1 2222 ____ 4444 5555 66
In order to achieve that, I'd have to allow the placeholder character as a valid MaskCharacter in every position. Which would be achievable by copying the entire class and modifying isValidCharacter()
, but that's dirty.
Is there a way to do something like?:
new MaskFormatter("[U^_][U^_][#^_][#^_] [#^_][#^_][#^_][#^_] [#^_][#^_][#^_][#^_] ...");
Or something like formatter.allowCharacter('_')
It does sort of work with "**** **** **** **** **** **", but that doesn't force the user to input valid characters at the given positions, so it's not really what I'm looking for.