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

时间:2014-04-03 05:35:19

标签: java swing jformattedtextfield

如果我只想接受字母和空格,FormatterFactoryJFormattedTextField的因子值是多少。

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

1 个答案:

答案 0 :(得分:0)

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

MaskFormatter mask = new MaskFormatter("*************"); // Specifies the number of characters allowed.
mask.setValidCharacters("qwertyuiopasdfghjklzxcvbnm" +
            "           QWERTYUIOPASDFGHJKLZXCVBNM "); // Specifies the valid characters: a-z, A-Z 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);

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


修改:使用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 a-z or A-Z 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;
    }
});

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