2015-04-21 32 views
1

我有一個JTexTField,我希望用戶輸入一個人的名字。我認爲該名稱應該包含[a-zA-Z],.space示例Mr. Bill。我正在使用DocumentFilter來驗證用戶輸入。但是,我無法弄清楚我應該如何在我的DocumentFilter中設置它。使用DocumentFilter過濾字符串,空格和點(。)的JTextField

問題:如何修改我的過濾器以實現上述行爲?

任何關於如何驗證一個人姓名的建議都被接受。

這裏是我的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(); 

     } 
     }); 
    } 
} 
+1

加一,但我缺少引號/標點符號,特別是單個 – mKorbel

+0

@mKorbel是的,我在想單個''',但不能決定它 - 例如'O'Rourke'。謝謝你提到它。 – JWizard

回答

2

你可以使用一個JFormattedTextFieldMaskFormatterMaskFormatter允許您指定有效字符的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

+0

除了使用蜂鳴聲之外,我能否通知用戶輸入了無效的輸入?我想通過消息對話框通知用戶。 – JWizard

+0

那麼,假設我已經訴諸你的實現,我該如何加入我的'正則表達式'來驗證'[a-zA-Z]'和'\ S'-白色空間?當我把它放在'setValidCharacters(「....」)'中時,它看起來如何? -謝謝。 – JWizard

+0

我提出了兩種不同的解決方案。一個是在你的DocumentFilter中使用正則表達式。我對編寫一個有效的正則表達式一無所知,因此我無法理解這些細節。第二個是使用JFormattedTextField。在這種情況下,創建一個簡單的包含JFormattedText字段的JFrame,然後測試我給出的3行代碼,以瞭解它是如何工作的。 – camickr

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 !"#$%&()*+,-/:;<=>[email protected][\]^_`{|}~ 
    //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 !"#$%&()*+,-/:;<=>[email protected][\]^_`{|}~ 
    fb.replace(off, len, str.replaceAll("^[0-9\\_\\(\\)@!\"#%&*+,\\-:;<>=?\\[\\]\\^\\~\\{\\}\\|\\/]", ""), attr); 
     } 

    } 

任何修改被接受,以滿足規定的驗證在原來的問題。