简体   繁体   中英

How to use JFormattedTextfield to accept names like strings?

What will be the FormatterFactory 's factor value in JFormattedTextField if I only want to accept letters and spaces.

Cause I want it to accepts Names only. Like - John Doe .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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