Java Reference
In-Depth Information
Validating the Contents of a JTextField
In a perfect world, users would only ever enter valid data into our applications. However, in
the real world, people make mistakes, and unfortunately, if not caught in time, major prob-
lems can occur if invalid data is entered. So we should make a reasonable effort to prevent
invalid data from being entered, and possibly validate data once it has been entered.
Listing 8-5 contained a field named zipCode . In the United States, zip codes are five digits
long, and are used to identify the area where a letter or parcel is to be delivered. Unfortunately,
our sample program will allow any data to be entered, regardless of length or content.
If we want to limit the zip code field to accept only five-digit zip codes, we can use a sub-
class of the JTextField : the JFormattedTextField in combination with a MaskFormatter . A
JFormattedTextField will only allow characters to be entered that match a specified mask. The
MaskFormatter provides a simple method of specifying a text formatter based on a mask—any
characters that do not match the mask will be discarded. The mask for a number is the # char-
acter. So we could change our definition of the zipCode variable from Listing 8-5 as follows:
MaskFormatter fiveDigits = new MaskFormatter("#####");
JTextField zipCode = new JFormattedTextField(fiveDigits);
zipCode.setColumns(5);
If you make these changes, you will find that you can no longer enter any character other
than a number, and you cannot add more than five digits.
Taking validation a step further, let's consider the case where users want to enter the zip+4
code, where the original five-digit code is followed by a dash and an additional four digits to
further narrow down the delivery address—for example, the first five digits specify the delivery
office (post office), the next two digits identify a set of blocks on a major street, and the final
two digits identify the particular block on the street.
However, zip+4 is not used everywhere, nor is it mandatory to use this format even where
it's available (for that matter, it does not appear to be mandatory to use zip codes for anything
going through the US Postal Service, but it is probably advisable if you want your letter to
arrive in a timely fashion).
One method of handling this is by creating our own text field, with its own document
model, in which we override the insertString method. So once again, our definition of the
zipCode variable is changing:
JTextField zipCode = new ZipTextField(9);
The ZipTextField extends JTextField , but all it overrides are the constructors and the
createDefaultModel method:
private class ZipTextField extends JTextField {
ZipTextField() {
super();
}
ZipTextField(int columns) {
super(columns);
}
Search WWH ::




Custom Search