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