如何使用JFormattedTextfield接受字符串之类的名称?

如果我只想接受字母和空格,那么在JFormattedTextField FormatterFactory的因子值是什么。

因为我希望它只接受名字。 喜欢 – John Doe

我找不到使用格式化程序的优雅方式。 非优雅的方法是创建一个MaskFormatter ,主要问题是限制允许的字符数(尽管你可以限制为任意大的数字)。

 MaskFormatter mask = new MaskFormatter("*************"); // Specifies the number of characters allowed. mask.setValidCharacters("qwertyuiopasdfghjklzxcvbnm" + " QWERTYUIOPASDFGHJKLZXCVBNM "); // Specifies the valid characters: az, AZ and space. mask.setPlaceholderCharacter(' '); // If the input is less characters than the mask, the space character will be used to fill the rest. Then you can use the trim method in String to get rid of them. JFormattedTextField textField = new JFormattedTextField(mask); 

我认为validation输入是比在这种情况下限制字符更好的方法。 如果你想使用这种方法,我可以添加一个例子。


编辑:使用InputVerifier ,您必须将其子类化并覆盖verify ,如下所示。

 JTextField textField = new JTextField(); textField.setInputVerifier(new InputVerifier() { @Override public boolean verify(JComponent input) { String text = ((JTextField) input).getText(); if (text.matches("[a-zA-Z ]+")) // Reads: "Any of az or AZ or space one or more times (together, not each)" ---> blank field or field containing anything other than those will return false. return true; return false; } }); 

在满足要求之前,文本字段不会产生焦点(父组件除外)。