Java JTextField Field Validator
Thursday, May 07, 2009
There are different ways to validate form fields in Java Swing applications, but the one I found the easiest to work with is extending
javax.swing.text.PlainDocument
.
If you use this method, field validation is accomplished in 2 easy steps.
Step 1Create a validator class, as follows:
public class OnlyNumberValidator extends javax.swing.text.PlainDocument {
@Override
public void insertString(int offs, String str,
javax.swing.text.AttributeSet a)
throws javax.swing.text.BadLocationException {
StringBuffer buf = new StringBuffer(str);
int size = buf.length();
char c;
for (int i = 0; i < size; i++) {
c = buf.charAt(i);
if (!Character.isDigit(c)) {
buf.deleteCharAt(i);
}
}
super.insertString(offs, buf.toString(), a);
}
}
The idea here is that every key stroke is accounted for. If the key stroke is a digit, we add it to the buffer and update the view; if it's not, we remove it from the buffer and update the view. The result is a field that doesn't allow unwanted characters.
Step 2Set a
Document
object to the field that needs validation, as follows:
// Assume you have the following JTextField object
javax.swing.JTextField jTextFieldOnlyNumber = new JTextField();
// We now set the validation
jTextFieldOnlyNumber.setDocument(new OnlyNumberValidator());
Simple as that. Now our
jTextFieldOnlyNumber
object only accepts numbers.
You can create more sophisticated validator classes by adding error checking and by limiting the type and number of characters per field. But the idea is the same: extend
javax.swing.text.PlainDocument
and override
insertString()
.
Comments:
Be careful with your algorithm for deleting characters from the StringBuffer, you will get an ArrayIndexOutOfBoundsException if the deleted character is not at the end of the String...
David, I don't understand what you mean. It's not deleting at the end of the buffer; it's deleting at buf.deleteCharAt(i), i.e., at every keystroke the loop checks all chars in the string and then deletes the one that is not a digit.
Perhaps I'm not seeing what you are seeing.