Java Reference
In-Depth Information
Input Masks
Beyond numbers and dates, the JFormattedTextField supports user input following a pattern
or mask. For instance, if an input field is a United States social security number (SSN), it has a
typical pattern of number, number, number, dash, number, number, dash, number, number,
number, number. With the help of the MaskFormatter class, you can specify the mask using the
characters listed in Table 16-9.
Table 16-9. Special Characters for Masks
Character
Description
#
Matches numeric character ( Character.isDigit() )
H
Matches hexadecimal number (0-9, a-f, and A-F)
A
Matches alphanumeric character ( Character.is LetterOrDigit() )
?
Matches alphabetic character ( Character.isLetter() )
U
Matches uppercase letter; maps lowercase to uppercase
L
Matches lowercase letter; maps uppercase to lowercase
*
Wildcard, matches any character
'
Escape character to have literal strings/separators in input field
For example, this formatter creates an SSN mask:
new MaskFormatter("###'-##'-####")
The apostrophes in the mask mean the character after each is treated literally—in this
case, as a dash. You have the option of passing this formatter to the JFormattedTextField
constructor or configuring the text field with the setMask() method.
To demonstrate, Listing 16-9 includes two JFormattedTextField components: one to
accept SSNs and the other United States phone numbers.
Listing 16-9. Formatted Masked Input
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.text.*;
import java.util.*;
public class MaskInputSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Mask Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
Search WWH ::




Custom Search