我有一個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();
}
});
}
}
加一,但我缺少引號/標點符號,特別是單個 – mKorbel
@mKorbel是的,我在想單個''',但不能決定它 - 例如'O'Rourke'。謝謝你提到它。 – JWizard