Java Reference
In-Depth Information
protected Document createDefaultModel() {
return new ZipDocument();
}
}
You could override more constructors if you wish, or you could even leave out the con-
structors (just use default constructors, and call the inherited setColumns method).
The hard work is all done in the model for our ZipTextField . For JTextField (which we
are subclassing), the default model is a PlainDocument . We will subclass that to form our
ZipDocument , in which we will validate text entered.
Note JTextField , like many Swing components, uses the Model-View-Controller design pattern inter-
nally. This gives us two potential areas where we can control data entry—in the Model that contains the
data entered, and in the Controller before data is passed to the Model.
private class ZipDocument extends PlainDocument {
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null) {
return;
}
for (char c : str.toCharArray()) {
if (! ((Character.isDigit(c) && offs < 10 && offs != 5)
|| (b == '-' && offs == 5))) {
return;
}
}
super.insertString(offs, str, a);
}
}
To keep this example simple, we have only overriden the insertString method, and only
checked that the character being entered is valid in the location it is being entered. If it is
valid, we call the insertString method of the super class to perform the work of actually
inserting the string.
Because we have chosen to keep this simple, we have not shown code for validating the
deletion of entered data for which we would have to override the remove method. A more com-
plete example is provided in the downloadable source code for this topic in the port number
validation.
Search WWH ::




Custom Search