简体   繁体   English

MaskFormatter中对jFormattedTextField的部分匹配

[英]Partial match in MaskFormatter for jFormattedTextField

How do I set up the MaskFormatter and the JFormattedTextField in order to allow partial matches? 如何设置MaskFormatter和JFormattedTextField以允许部分匹配?

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). 我希望用户能够使用此掩码“ ## ###### ####”输入数字,因此,如果用户输入“ 123456789123”,格式化程序会将其更改为“ 12 345678 9123”(它会添加空格)在第2个和第8个字符之后)。

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()) 但是,我也希望用户能够输入'12346578',将其转换为'12 345678'并仍然是有效值(因此我可以使用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() 我尝试将focusLostBehavior设置为PERSIST,因此退出jFormattedTextField1后不会清除该值,但是那样我在使用调用jFormattedTextField1.getValue()时会得到null

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. 然后,我总是可以修剪通过getValue()获得的字符串,以删除尾随空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM