简体   繁体   中英

Filtering a JTextField for strings, space and a dot (.) using a DocumentFilter

I have a JTexTField that I would want a user to enter the name of a person. I have figured that the name should contain [a-zA-Z] , . and space example Mr. Bill . I am using a DocumentFilter to validate user input.However, I cannot figure out how should I set this within my DocumentFilter .

Question: How should I modify my filter to achieve the above behavior?

Any suggestion on how to validate a person's name is accepted.

Here is my DocumentFilter:

public class NameValidator extends DocumentFilter{
@Override
public void insertString(DocumentFilter.FilterBypass fp, int offset,
        String string, AttributeSet aset) throws BadLocationException {
    int len = string.length();
    boolean isValidInteger = true;

    for (int i = 0; i < len; i++) {
        if (!Character.isLetter(string.charAt(i))) {
            isValidInteger = false;
            break;
        }
    }
    if (isValidInteger)
        super.insertString(fp, offset, string, aset);
    else {
        JOptionPane.showMessageDialog(null,
                "Please Valid Letters only.", "Invalid Input : ",
                JOptionPane.ERROR_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
    }
}

@Override
public void replace(DocumentFilter.FilterBypass fp, int offset, int length,
        String string, AttributeSet aset) throws BadLocationException {
    int len = string.length();
    boolean isValidInteger = true;

    for (int i = 0; i < len; i++) {
        if (!Character.isLetter(string.charAt(i)) ) {
            isValidInteger = false;
            break;
        }
    }
    if (isValidInteger)
        super.replace(fp, offset, length, string, aset);
    else {
        JOptionPane.showMessageDialog(null,
                "Please Valid Letters only.", "Invalid Input : ",
                JOptionPane.ERROR_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
     }
   }
 }

Here is my test class:

public class NameTest {

private JFrame frame;

public NameTest() {
    frame = new JFrame();
    initGui();
}

private void initGui() {

    frame.setSize(100, 100);
    frame.setVisible(true);
    frame.setLayout(new GridLayout(2, 1, 5, 5));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField name = new JTextField(15);
    ((AbstractDocument) name.getDocument())
            .setDocumentFilter(new NameValidator());
    frame.add(name);

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            NameTest nt = new NameTest();

         }
      });
    }
 }

You could use a JFormattedTextField with a MaskFormatter . The MaskFormatter allows you to specify a String of valid characters.

MaskFormatter mf = new MaskFormatter( "***************" );
mf.setValidCharacters(" .abcABC");
JFormattedTextField ftf = new JFormattedTextField( mf );

Behind the scenes the formatted text field uses a DocumentFilter. Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and examples.

You can also try searching the forum/web for a regex DocumentFilter. This type of filter is generally reusable because you just need to specify the regex expression. For example: Trouble using regex in DocumentFilter for JTextField

The solution I found might be necessary for modifications to address all the validations I mentioned above. I have used DocumentFilter to eliminate \\p{Punct} - except for . and ' from this set and [0 -9] .

Here is the code that I used:

public class NameValidator extends DocumentFilter{
@Override
public void insertString(FilterBypass fb, int off
                    , String str, AttributeSet attr) 
                            throws BadLocationException 
{
    // remove 0-9 !"#$%&()*+,-/:;<=>?@[\]^_`{|}~
    //back space character is skipped here!
    fb.insertString(off, str.replaceAll("^[0-9\\_\\(\\)@!\"#%&*+,\\-:;<>=?\\[\\]\\^\\~\\{\\}\\|\\/]", ""), attr);
} 
@Override
public void replace(FilterBypass fb, int off
        , int len, String str, AttributeSet attr) 
                        throws BadLocationException 
{
    // remove 0-9 !"#$%&()*+,-/:;<=>?@[\]^_`{|}~
    fb.replace(off, len, str.replaceAll("^[0-9\\_\\(\\)@!\"#%&*+,\\-:;<>=?\\[\\]\\^\\~\\{\\}\\|\\/]", ""), attr);
       }

  }

Any modification are accepted to suit the stipulated validation in the original question.

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