在NetBeans中,如何为JFormattedTextField
设置无效字符,以便它不允许:|
,[
,]
等?
没关系,我找到了解决方案:
MaskFormatter formatter = null;
try {
//# - Any valid number, uses Character.isDigit.
//' - Escape character, used to escape any of the special formatting characters.
//U - Any character (Character.isLetter). All lowercase letters are mapped to upper case.
//L - Any character (Character.isLetter). All upper case letters are mapped to lower case.
//A - Any character or number (Character.isLetter or Character.isDigit)
//? - Any character (Character.isLetter).
//* - Anything.
//H - Any hex character (0-9, a-f or A-F).
formatter = new MaskFormatter("******************************");
formatter.setInvalidCharacters("|[]");
} catch (java.text.ParseException ex) {
}
然后,在GUI上右键单击JFormattedTextField,单击Customize Code,在myFormattedTextField = new javax.swing.JFormattedTextField();
旁边的下拉框中选择自定义创建,并将格式化程序添加到JFormattedTextField,如下所示:myFormattedTextField = new javax.swing.JFormattedTextField(formatter);
希望有一天能帮助别人。
答案 0 :(得分:1)
最舒适的方式是添加DocumentListener并且Pattern,JFormattedTextField
的valur可以插入(字符块)或者通过char添加char,我建议覆盖这两种方法
insertUpdate()
changedUpdate()//Plain text components don't fire these events.
对于插入的字符块,可以更好地直接实现Pattern p = Pattern.compile("decision char filtering")