262
|
Chapter 7, Text
#49 Force Text Input into Specific Formats
HACK
Constraining a Document
Hopefully, you won’t be surprised to know that you don’t need to touch the
view classes—
JTextField, JTextArea, etc.—to add text constraint function-
ality. Text entry is happening in the model—in other words the
Document
so that’s where you tie in your regex code. This hack, listed in Example 7-2,
subclasses
PlainDocument
to run the regex check on every call to
insertString( )
.
Example 7-2. A document allowing input that matches only a regex
import javax.swing.text.*;
import java.util.regex.*;
public class RegexConstrainedDocument extends PlainDocument {
Pattern pattern;
Matcher matcher;
public RegexConstrainedDocument () { super( ); }
public RegexConstrainedDocument (AbstractDocument.Content c) { super(c); }
public RegexConstrainedDocument (AbstractDocument.Content c, String p) {
super (c);
setPatternByString (p);
}
public RegexConstrainedDocument (String p) {
super( );
setPatternByString (p);
}
public void setPatternByString (String p) {
Pattern pattern = Pattern.compile (p);
// checks the document against the new pattern
// and removes the content if it no longer matches
try {
matcher = pattern.matcher (getText(0, getLength( )));
System.out.println ("matcher reset to " +
getText (0, getLength( )));
if (! matcher.matches( )) {
System.out.println ("does not match");
remove (0, getLength( ));
}
} catch (BadLocationException ble) {
ble.printStackTrace( ); // impossible?
}
}
public Pattern getPattern( ) { return pattern; }
public void insertString (int offs, String s, AttributeSet a)
throws BadLocationException {

Get Swing Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.