How to use JFormattedTextfield to accept names like strings?

ε祈祈猫儿з 提交于 2019-12-04 16:34:44

I couldn't find an elegant way using a formatter. The non-elegant way is to create a MaskFormatter with the main issue that you will be limiting the number of characters allowed (although you can limit to an arbitrarily large number).

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);

I feel that validating the input is a better approach than restricting characters in this case. I can add an example if you want to use this approach.


Edit: Using InputVerifier, you have to subclass it and override verify as shown below.

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;
    }
});

The text field will not yield focus (except to parent components) until requirements are met.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!