使用DocumentFilter过滤字符串,空格和点(。)的JTextField

时间:2015-04-21 15:40:38

标签: java swing validation jtextfield documentfilter

我有一个JTexTField,我希望用户输入一个人的姓名。我认为该名称应包含[a-zA-Z].space示例 Mr. Bill 。我使用DocumentFilter来验证用户输入。但是,我无法弄清楚应该如何在DocumentFilter中设置它。

问题:如何修改我的过滤器以实现上述行为?

接受任何有关如何验证某人姓名的建议。

这是我的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();
     }
   }
 }

这是我的测试类:

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

         }
      });
    }
 }

2 个答案:

答案 0 :(得分:2)

您可以将JFormattedTextFieldMaskFormatter一起使用。 MaskFormatter允许您指定String个有效字符。

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

在幕后,格式化文本字段使用DocumentFilter。阅读How to Use Formatted Text Fields上Swing教程中的部分,了解更多信息和示例。

您还可以尝试在论坛/网站上搜索正则表达式DocumentFilter。这种类型的过滤器通常是可重用的,因为您只需要指定正则表达式。例如:Trouble using regex in DocumentFilter for JTextField

答案 1 :(得分:0)

我找到的解决方案可能需要进行修改以解决我上面提到的所有验证问题。我已使用DocumentFilter来消除\p{Punct} - 此集合中的.'以及[0 -9]除外。

以下是我使用的代码:

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

  }

接受任何修改以适应原始问题中的规定验证。