开发者

Partial match in MaskFormatter for jFormattedTextField

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 numbe开发者_C百科rs 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()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜