
Force Text Input into Specific Formats #49
Chapter 7, Text
|
263
HACK
This class holds onto a Pattern and a Matcher to perform the regex match-
ing. The pattern can be set in the constructor, or later with a call to
setPatternByString( ). In either case, the method compiles the pattern and
creates a
Matcher with the Document’s text. Changing the pattern could, of
course, create a mismatch with any existing text in the
Document, so the
Matcher immediately calls matches( ) and if the text does not match, it
deletes all the text from the
Document.
Perhaps the more typical case is when the
Document.insertString() method is
called. This will happen on every keystroke in a
JTextComponent. Assuming the
Matcher is not null, meaning that the Pattern has been set at some point, you
simply need to call
Matcher.matches( ) against the Document’s new contents to
see if they comply with the regex constraints. If not, return early, never call-
ing the superclass’s
insert( ) method, and thus disallowing the input.
Adding Constrained Text Fields
Since the Document isn’t actually visible, you need to put it in something in
order to test it. The
TestRegexConstrainedDocument class creates a JTextField
for you to type in a regular expression to enforce, and a longer JTextField
for text to test. You create this latter JTextField with the seldom-seen con-
structor that takes a
Document, an initial-value String, and a width (specified ...