O'Reilly logo

Java Swing, 2nd Edition by Brian Cole, James Elliott, Marc Loy, Robert Eckstein, Dave Wood

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

The MaskFormatter Class

MaskFormatter is a subclass of DefaultFormatter that formats strings by matching them against a mask. The mask is a string of literals and nonliterals. The nonliterals (listed and described in Table 20-4) are wildcards that match a family of characters. Literals match only themselves. A single quote preceding a nonliteral (or another single quote) turns it into a literal. So, for example, the mask "ABa'A#''Hb" consists of the nonliteral A, the literal B, the literal a, the literal A, the nonliteral #, the literal ', the nonliteral H, and the literal b. The string "1BaA1'1b" matches this mask.

Table 20-4. Mask nonliterals (case-sensitive)

char

Matches

Notes

*

Any character

 

A

Any alphanumeric character

Tested by Character.isLetterOrDigit( )

?

Any alphabetic character

Tested by Character.isLetter( )

U

Uppercase alphabetic

Like ? but lowercase is mapped to uppercase

L

Lowercase alphabetic

Like ? but uppercase is mapped to lowercase

#

Any numeric character

Tested by Character.isDigit( )

H

Any hexadecimal numeric

Like # but includes abcdefABCDEF

'

 

Precedes any character in this table to create a literal

The JFormattedTextField in Figure 19-1 (and the code that follows it) uses a simple MaskFormatter with mask "UUUUU".

A MaskFormatter installed on a JFormattedTextField controls the caret so that by default it skips over literals and lands on nonliterals, which is nice. It can also be configured (by setting the valueContainsLiteralCharacters property to false) to have getValue( ...

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