javax.swing.text
Class MaskFormatter

java.lang.Object
  extended byjavax.swing.JFormattedTextField.AbstractFormatter
      extended byjavax.swing.text.DefaultFormatter
          extended byjavax.swing.text.MaskFormatter
All Implemented Interfaces:
Cloneable, Serializable

public class MaskFormatter
extends DefaultFormatter

MaskFormatter is used to format and edit strings. The behavior of a MaskFormatter is controlled by way of a String mask that specifies the valid characters that can be contained at a particular location in the Document model. The following characters can be specified:

Character 

Description

# Any valid number, uses Character.isDigit.
' Escape character, used to escape any of the special formatting characters.
UAny character (Character.isLetter). All lowercase letters are mapped to upper case.
LAny character (Character.isLetter). All upper case letters are mapped to lower case.
AAny character or number (Character.isLetter or Character.isDigit)
?Any character (Character.isLetter).
*Anything.
HAny hex character (0-9, a-f or A-F).

Typically characters correspond to one char, but in certain languages this is not the case. The mask is on a per character basis, and will thus adjust to fit as many chars as are needed.

You can further restrict the characters that can be input by the setInvalidCharacters and setValidCharacters methods. setInvalidCharacters allows you to specify which characters are not legal. setValidCharacters allows you to specify which characters are valid. For example, the following code block is equivalent to a mask of '0xHHH' with no invalid/valid characters:

 MaskFormatter formatter = new MaskFormatter("0x***");
 formatter.setValidCharacters("0123456789abcdefABCDEF");
 

When initially formatting a value if the length of the string is less than the length of the mask, two things can happen. Either the placeholder string will be used, or the placeholder character will be used. Precedence is given to the placeholder string. For example:

   MaskFormatter formatter = new MaskFormatter("###-####");
   formatter.setPlaceholderCharacter('_');
   formatter.getDisplayValue(tf, "123");
 

Would result in the string '123-____'. If setPlaceholder("555-1212") was invoked '123-1212' would result. The placeholder String is only used on the initial format, on subsequent formats only the placeholder character will be used.

If a MaskFormatter is configured to only allow valid characters (setAllowsInvalid(false)) literal characters will be skipped as necessary when editing. Consider a MaskFormatter with the mask "###-####" and current value "555-1212". Using the right arrow key to navigate through the field will result in (| indicates the position of the caret):

   |555-1212
   5|55-1212
   55|5-1212
   555-|1212
   555-1|212
 
The '-' is a literal (non-editable) character, and is skipped.

Similar behavior will result when editing. Consider inserting the string '123-45' and '12345' into the MaskFormatter in the previous example. Both inserts will result in the same String, '123-45__'. When MaskFormatter is processing the insert at character position 3 (the '-'), two things can happen:

  1. If the inserted character is '-', it is accepted.
  2. If the inserted character matches the mask for the next non-literal character, it is accepted at the new location.
  3. Anything else results in an invalid edit

By default MaskFormatter will not allow invalid edits, you can change this with the setAllowsInvalid method, and will commit edits on valid edits (use the setCommitsOnValidEdit to change this).

By default, MaskFormatter is in overwrite mode. That is as characters are typed a new character is not inserted, rather the character at the current location is replaced with the newly typed character. You can change this behavior by way of the method setOverwriteMode.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see XMLEncoder.

Since:
1.4
See Also:
Serialized Form

Nested Class Summary
private  class MaskFormatter.AlphaNumericCharacter
          Represents either a character or digit, uses Character.isLetterOrDigit.
private  class MaskFormatter.CharCharacter
          Represents a letter, uses Character.isLetter.
private  class MaskFormatter.DigitMaskCharacter
          Represents a number, uses Character.isDigit.
private  class MaskFormatter.HexCharacter
          Represents a hex character, 0-9a-fA-F. a-f is mapped to A-F
private  class MaskFormatter.LiteralCharacter
          Used to represent a fixed character in the mask.
private  class MaskFormatter.LowerCaseCharacter
          Represents a character, upper case letters are mapped to lower case using Character.toLowerCase.
private  class MaskFormatter.MaskCharacter
           
private  class MaskFormatter.UpperCaseCharacter
          Represents a character, lower case letters are mapped to upper case using Character.toUpperCase.
 
Nested classes inherited from class javax.swing.text.DefaultFormatter
DefaultFormatter.ReplaceHolder
 
Field Summary
private static char ALPHA_NUMERIC_KEY
           
private static char ANYTHING_KEY
           
private static char CHARACTER_KEY
           
private  boolean containsLiteralChars
          Indicates if the value contains the literal characters.
private static char DIGIT_KEY
           
private static MaskFormatter.MaskCharacter[] EmptyMaskChars
           
private static char HEX_KEY
           
private  String invalidCharacters
          List of invalid characters.
private static char LITERAL_KEY
           
private static char LOWERCASE_KEY
           
private  String mask
          The user specified mask.
private  MaskFormatter.MaskCharacter[] maskChars
           
private  char placeholder
          String used to represent characters not present.
private  String placeholderString
          String used for the passed in value if it does not completely fill the mask.
private static char UPPERCASE_KEY
           
private  String validCharacters
          List of valid characters.
 
Fields inherited from class javax.swing.text.DefaultFormatter
replaceHolder
 
Fields inherited from class javax.swing.JFormattedTextField.AbstractFormatter
 
Constructor Summary
MaskFormatter()
          Creates a MaskFormatter with no mask.
MaskFormatter(String mask)
          Creates a MaskFormatter with the specified mask.
 
Method Summary
private  void append(StringBuffer result, String value, int[] index, String placeholder, MaskFormatter.MaskCharacter[] mask)
          Invokes append on the mask characters in mask.
(package private)  boolean canReplace(DefaultFormatter.ReplaceHolder rh)
          This method does the following (assuming !
private  char getCharacter(int index, char aChar)
          Returns the character to insert at the specified location based on the passed in character.
 String getInvalidCharacters()
          Returns the characters that are not valid for input.
private  int getInvalidOffset(String string, boolean completeMatch)
          Returns -1 if the passed in string is valid, otherwise the index of the first bogus character is returned.
private  char getLiteral(int index)
          Returns the literal character at the specified location.
 String getMask()
          Returns the formatting mask.
private  MaskFormatter.MaskCharacter getMaskCharacter(int index)
          Returns the MaskCharacter at the specified location.
private  int getMaxLength()
          Returns the maximum length the text can be.
 String getPlaceholder()
          Returns the String to use if the value does not completely fill in the mask.
 char getPlaceholderCharacter()
          Returns the character to use in place of characters that are not present in the value, ie the user must fill them in.
 String getValidCharacters()
          Returns the valid characters that can be input.
 boolean getValueContainsLiteralCharacters()
          Returns true if stringToValue should return literal characters in the mask.
 void install(JFormattedTextField ftf)
          Installs the DefaultFormatter onto a particular JFormattedTextField.
private  boolean isLiteral(int index)
          Returns true if the character at the specified location is a literal, that is it can not be edited.
(package private)  boolean isNavigatable(int offset)
          Returns true if the MaskFormatter allows invalid, or the offset is less than the max length and the character at offset is a literal.
private  boolean isPlaceholder(int index, char aChar)
          Returns true if the placeholder character matches aChar.
private  boolean isValidCharacter(int index, char aChar)
          Returns true if the passed in character matches the mask at the specified location.
(package private)  boolean isValidEdit(DefaultFormatter.ReplaceHolder rh)
           
private  void readObject(ObjectInputStream s)
          Subclassed to update the internal representation of the mask after the default read operation has completed.
 void setInvalidCharacters(String invalidCharacters)
          Allows for further restricting of the characters that can be input.
 void setMask(String mask)
          Sets the mask dictating the legal characters.
 void setPlaceholder(String placeholder)
          Sets the string to use if the value does not completely fill in the mask.
 void setPlaceholderCharacter(char placeholder)
          Sets the character to use in place of characters that are not present in the value, ie the user must fill them in.
 void setValidCharacters(String validCharacters)
          Allows for further restricting of the characters that can be input.
 void setValueContainsLiteralCharacters(boolean containsLiteralChars)
          If true, the returned value and set value will also contain the literal characters in mask.
 Object stringToValue(String value)
          Parses the text, returning the appropriate Object representation of the String value.
private  Object stringToValue(String value, boolean completeMatch)
          Actual stringToValue implementation.
private  String stripLiteralChars(String string)
          Removes the literal characters from the passed in string.
private  void updateInternalMask()
          Updates the internal representation of the mask.
 String valueToString(Object value)
          Returns a String representation of the Object value based on the mask.
 
Methods inherited from class javax.swing.text.DefaultFormatter
clone, commitEdit, getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getInitialVisualPosition, getNavigationFilter, getNextCursorPosition, getNextVisualPositionFrom, getOverwriteMode, getReplaceHolder, getReplaceString, getValueClass, isLegalInsertText, moveDot, positionCursorAtInitialLocation, replace, replace, repositionCursor, setAllowsInvalid, setCommitsOnValidEdit, setDot, setOverwriteMode, setValueClass, updateValue, updateValue
 
Methods inherited from class javax.swing.JFormattedTextField.AbstractFormatter
getActions, getFormattedTextField, invalidEdit, setEditValid, uninstall
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

DIGIT_KEY

private static final char DIGIT_KEY
See Also:
Constant Field Values

LITERAL_KEY

private static final char LITERAL_KEY
See Also:
Constant Field Values

UPPERCASE_KEY

private static final char UPPERCASE_KEY
See Also:
Constant Field Values

LOWERCASE_KEY

private static final char LOWERCASE_KEY
See Also:
Constant Field Values

ALPHA_NUMERIC_KEY

private static final char ALPHA_NUMERIC_KEY
See Also:
Constant Field Values

CHARACTER_KEY

private static final char CHARACTER_KEY
See Also:
Constant Field Values

ANYTHING_KEY

private static final char ANYTHING_KEY
See Also:
Constant Field Values

HEX_KEY

private static final char HEX_KEY
See Also:
Constant Field Values

EmptyMaskChars

private static final MaskFormatter.MaskCharacter[] EmptyMaskChars

mask

private String mask
The user specified mask.


maskChars

private transient MaskFormatter.MaskCharacter[] maskChars

validCharacters

private String validCharacters
List of valid characters.


invalidCharacters

private String invalidCharacters
List of invalid characters.


placeholderString

private String placeholderString
String used for the passed in value if it does not completely fill the mask.


placeholder

private char placeholder
String used to represent characters not present.


containsLiteralChars

private boolean containsLiteralChars
Indicates if the value contains the literal characters.

Constructor Detail

MaskFormatter

public MaskFormatter()
Creates a MaskFormatter with no mask.


MaskFormatter

public MaskFormatter(String mask)
              throws ParseException
Creates a MaskFormatter with the specified mask. A ParseException will be thrown if mask is an invalid mask.

Throws:
ParseException - if mask does not contain valid mask characters
Method Detail

setMask

public void setMask(String mask)
             throws ParseException
Sets the mask dictating the legal characters. This will throw a ParseException if mask is not valid.

Throws:
ParseException - if mask does not contain valid mask characters

getMask

public String getMask()
Returns the formatting mask.

Returns:
Mask dictating legal character values.

setValidCharacters

public void setValidCharacters(String validCharacters)
Allows for further restricting of the characters that can be input. Only characters specified in the mask, not in the invalidCharacters, and in validCharacters will be allowed to be input. Passing in null (the default) implies the valid characters are only bound by the mask and the invalid characters.

Parameters:
validCharacters - If non-null, specifies legal characters.

getValidCharacters

public String getValidCharacters()
Returns the valid characters that can be input.

Returns:
Legal characters

setInvalidCharacters

public void setInvalidCharacters(String invalidCharacters)
Allows for further restricting of the characters that can be input. Only characters specified in the mask, not in the invalidCharacters, and in validCharacters will be allowed to be input. Passing in null (the default) implies the valid characters are only bound by the mask and the valid characters.

Parameters:
invalidCharacters - If non-null, specifies illegal characters.

getInvalidCharacters

public String getInvalidCharacters()
Returns the characters that are not valid for input.

Returns:
illegal characters.

setPlaceholder

public void setPlaceholder(String placeholder)
Sets the string to use if the value does not completely fill in the mask. A null value implies the placeholder char should be used.

Parameters:
placeholder - String used when formatting if the value does not completely fill the mask

getPlaceholder

public String getPlaceholder()
Returns the String to use if the value does not completely fill in the mask.

Returns:
String used when formatting if the value does not completely fill the mask

setPlaceholderCharacter

public void setPlaceholderCharacter(char placeholder)
Sets the character to use in place of characters that are not present in the value, ie the user must fill them in. The default value is a space.

This is only applicable if the placeholder string has not been specified, or does not completely fill in the mask.

Parameters:
placeholder - Character used when formatting if the value does not completely fill the mask

getPlaceholderCharacter

public char getPlaceholderCharacter()
Returns the character to use in place of characters that are not present in the value, ie the user must fill them in.

Returns:
Character used when formatting if the value does not completely fill the mask

setValueContainsLiteralCharacters

public void setValueContainsLiteralCharacters(boolean containsLiteralChars)
If true, the returned value and set value will also contain the literal characters in mask.

For example, if the mask is '(###) ###-####', the current value is '(415) 555-1212', and valueContainsLiteralCharacters is true stringToValue will return '(415) 555-1212'. On the other hand, if valueContainsLiteralCharacters is false, stringToValue will return '4155551212'.

Parameters:
containsLiteralChars - Used to indicate if literal characters in mask should be returned in stringToValue

getValueContainsLiteralCharacters

public boolean getValueContainsLiteralCharacters()
Returns true if stringToValue should return literal characters in the mask.

Returns:
True if literal characters in mask should be returned in stringToValue

stringToValue

public Object stringToValue(String value)
                     throws ParseException
Parses the text, returning the appropriate Object representation of the String value. This strips the literal characters as necessary and invokes supers stringToValue, so that if you have specified a value class (setValueClass) an instance of it will be created. This will thrown a ParseException if the value does not match the current mask.

Overrides:
stringToValue in class DefaultFormatter
Parameters:
value - String to convert
Returns:
Object representation of text
Throws:
ParseException - if there is an error in the conversion

valueToString

public String valueToString(Object value)
                     throws ParseException
Returns a String representation of the Object value based on the mask.

Overrides:
valueToString in class DefaultFormatter
Parameters:
value - Value to convert
Returns:
String representation of value
Throws:
ParseException - if there is an error in the conversion

install

public void install(JFormattedTextField ftf)
Installs the DefaultFormatter onto a particular JFormattedTextField. This will invoke valueToString to convert the current value from the JFormattedTextField to a String. This will then install the Actions from getActions, the DocumentFilter returned from getDocumentFilter and the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.

Subclasses will typically only need to override this if they wish to install additional listeners on the JFormattedTextField.

If there is a ParseException in converting the current value to a String, this will set the text to an empty String, and mark the JFormattedTextField as being in an invalid state.

While this is a public method, this is typically only useful for subclassers of JFormattedTextField. JFormattedTextField will invoke this method at the appropriate times when the value changes, or its internal state changes.

Overrides:
install in class DefaultFormatter
Parameters:
ftf - JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.

stringToValue

private Object stringToValue(String value,
                             boolean completeMatch)
                      throws ParseException
Actual stringToValue implementation. If completeMatch is true, the value must exactly match the mask, on the other hand if completeMatch is false the string must match the mask or the placeholder string.

Throws:
ParseException

getInvalidOffset

private int getInvalidOffset(String string,
                             boolean completeMatch)
Returns -1 if the passed in string is valid, otherwise the index of the first bogus character is returned.


append

private void append(StringBuffer result,
                    String value,
                    int[] index,
                    String placeholder,
                    MaskFormatter.MaskCharacter[] mask)
             throws ParseException
Invokes append on the mask characters in mask.

Throws:
ParseException

updateInternalMask

private void updateInternalMask()
                         throws ParseException
Updates the internal representation of the mask.

Throws:
ParseException

getMaskCharacter

private MaskFormatter.MaskCharacter getMaskCharacter(int index)
Returns the MaskCharacter at the specified location.


isPlaceholder

private boolean isPlaceholder(int index,
                              char aChar)
Returns true if the placeholder character matches aChar.


isValidCharacter

private boolean isValidCharacter(int index,
                                 char aChar)
Returns true if the passed in character matches the mask at the specified location.


isLiteral

private boolean isLiteral(int index)
Returns true if the character at the specified location is a literal, that is it can not be edited.


getMaxLength

private int getMaxLength()
Returns the maximum length the text can be.


getLiteral

private char getLiteral(int index)
Returns the literal character at the specified location.


getCharacter

private char getCharacter(int index,
                          char aChar)
Returns the character to insert at the specified location based on the passed in character. This provides a way to map certain sets of characters to alternative values (lowercase to uppercase...).


stripLiteralChars

private String stripLiteralChars(String string)
Removes the literal characters from the passed in string.


readObject

private void readObject(ObjectInputStream s)
                 throws IOException,
                        ClassNotFoundException
Subclassed to update the internal representation of the mask after the default read operation has completed.

Throws:
IOException
ClassNotFoundException

isNavigatable

boolean isNavigatable(int offset)
Returns true if the MaskFormatter allows invalid, or the offset is less than the max length and the character at offset is a literal.

Overrides:
isNavigatable in class DefaultFormatter

isValidEdit

boolean isValidEdit(DefaultFormatter.ReplaceHolder rh)
Overrides:
isValidEdit in class DefaultFormatter

canReplace

boolean canReplace(DefaultFormatter.ReplaceHolder rh)
This method does the following (assuming !getAllowsInvalid()): iterate over the max of the deleted region or the text length, for each character:
  1. If it is valid (matches the mask at the particular position, or matches the literal character at the position), allow it
  2. Else if the position identifies a literal character, add it. This allows for the user to paste in text that may/may not contain the literals. For example, in pasing in 5551212 into ###-#### when the 1 is evaluated it is illegal (by the first test), but there is a literal at this position (-), so it is used. NOTE: This has a problem that you can't tell (without looking ahead) if you should eat literals in the text. For example, if you paste '555' into #5##, should it result in '5555' or '555 '? The current code will result in the latter, which feels a little better as selecting text than pasting will always result in the same thing.
  3. Else if at the end of the inserted text, the replace the item with the placeholder
  4. Otherwise the insert is bogus and false is returned.

Overrides:
canReplace in class DefaultFormatter