O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 {

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required