tags:

views:

129

answers:

1

How do I set up the MaskFormatter and the JFormattedTextField in order to allow partial matches?

For example:

I want the user to be able to enter numbers with this mask "## ###### ####", so if the user enters '123456789123' the formatter changes it to '12 345678 9123' (it adds spaces after the 2nd and 8th characters).

However, I also want the user to be able to enter '12346578', be converted to '12 345678' and still be a valid value (so I can get it using jFormatedTextField1.getValue())

This is part of my code:

JFormattedTextField jFormattedTextField1;
MaskFormatter mf;

mf = new MaskFormatter("## ###### ####");
jFormattedTextField1.setFormatterFactory(new DefaultFormatterFactory(mf));

I've tried setting the focusLostBehavior to PERSIST so the value is not cleard after exiting the jFormattedTextField1, but that way I get a null when using the calling jFormattedTextField1.getValue()

A: 

Solved it by setting the mask using asterisks and the setting its valid characters as numbers and the space character too.

JFormattedTextField jFormattedTextField1;
MaskFormatter mf;

mf = new MaskFormatter("** ****** ****");
mf.setValidCharacters("0123456789 ");
jFormattedTextField1.setFormatterFactory(new DefaultFormatterFactory(mf));

Then I can always trim the string I get with getValue() in order to remove the trailing spaces.

Toto