javax.swing.text
public class: MaskFormatter [javadoc |
source]
java.lang.Object
javax.swing.JFormattedTextField.AbstractFormatter
javax.swing.text.DefaultFormatter
javax.swing.text.MaskFormatter
All Implemented Interfaces:
Cloneable, Serializable
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. |
U | Any character (Character.isLetter ). All
lowercase letters are mapped to upper case. |
L | Any character (Character.isLetter ). All
upper case letters are mapped to lower case. |
A | Any character or number (Character.isLetter
or Character.isDigit ) |
? | Any character
(Character.isLetter ). |
* | Anything. |
H | Any 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:
- If the inserted character is '-', it is accepted.
- If the inserted character matches the mask for the next non-literal
character, it is accepted at the new location.
- 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 java.beans.XMLEncoder .
Method from javax.swing.text.MaskFormatter Summary: |
---|
canReplace, getInvalidCharacters, getMask, getPlaceholder, getPlaceholderCharacter, getValidCharacters, getValueContainsLiteralCharacters, install, isNavigatable, isValidEdit, setInvalidCharacters, setMask, setPlaceholder, setPlaceholderCharacter, setValidCharacters, setValueContainsLiteralCharacters, stringToValue, valueToString |
Methods from javax.swing.text.DefaultFormatter: |
---|
canReplace, clone, commitEdit, getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getInitialVisualPosition, getNavigationFilter, getNextCursorPosition, getNextVisualPositionFrom, getOverwriteMode, getReplaceHolder, getReplaceString, getValueClass, install, isLegalInsertText, isNavigatable, isValidEdit, moveDot, positionCursorAtInitialLocation, replace, replace, repositionCursor, setAllowsInvalid, setCommitsOnValidEdit, setDot, setOverwriteMode, setValueClass, stringToValue, updateValue, updateValue, valueToString |
Methods from javax.swing.JFormattedTextField$AbstractFormatter: |
---|
clone, getActions, getDocumentFilter, getFormattedTextField, getNavigationFilter, install, invalidEdit, setEditValid, stringToValue, uninstall, valueToString |
Methods from java.lang.Object: |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Method from javax.swing.text.MaskFormatter Detail: |
boolean canReplace(ReplaceHolder rh) {
// This method is rather long, but much of the burden is in
// maintaining a String and swapping to a StringBuilder only if
// absolutely necessary.
if (!getAllowsInvalid()) {
StringBuilder replace = null;
String text = rh.text;
int tl = (text != null) ? text.length() : 0;
if (tl == 0 && rh.length == 1 && getFormattedTextField().
getSelectionStart() != rh.offset) {
// Backspace, adjust to actually delete next non-literal.
while (rh.offset > 0 && isLiteral(rh.offset)) {
rh.offset--;
}
}
int max = Math.min(getMaxLength() - rh.offset,
Math.max(tl, rh.length));
for (int counter = 0, textIndex = 0; counter < max; counter++) {
if (textIndex < tl && isValidCharacter(rh.offset + counter,
text.charAt(textIndex))) {
char aChar = text.charAt(textIndex);
if (aChar != getCharacter(rh.offset + counter, aChar)) {
if (replace == null) {
replace = new StringBuilder();
if (textIndex > 0) {
replace.append(text.substring(0, textIndex));
}
}
}
if (replace != null) {
replace.append(getCharacter(rh.offset + counter,
aChar));
}
textIndex++;
}
else if (isLiteral(rh.offset + counter)) {
if (replace != null) {
replace.append(getLiteral(rh.offset + counter));
if (textIndex < tl) {
max = Math.min(max + 1, getMaxLength() -
rh.offset);
}
}
else if (textIndex > 0) {
replace = new StringBuilder(max);
replace.append(text.substring(0, textIndex));
replace.append(getLiteral(rh.offset + counter));
if (textIndex < tl) {
// Evaluate the character in text again.
max = Math.min(max + 1, getMaxLength() -
rh.offset);
}
else if (rh.cursorPosition == -1) {
rh.cursorPosition = rh.offset + counter;
}
}
else {
rh.offset++;
rh.length--;
counter--;
max--;
}
}
else if (textIndex >= tl) {
// placeholder
if (replace == null) {
replace = new StringBuilder();
if (text != null) {
replace.append(text);
}
}
replace.append(getPlaceholderCharacter());
if (tl > 0 && rh.cursorPosition == -1) {
rh.cursorPosition = rh.offset + counter;
}
}
else {
// Bogus character.
return false;
}
}
if (replace != null) {
rh.text = replace.toString();
}
else if (text != null && rh.offset + tl > getMaxLength()) {
rh.text = text.substring(0, getMaxLength() - rh.offset);
}
if (getOverwriteMode() && rh.text != null) {
rh.length = rh.text.length();
}
}
return super.canReplace(rh);
}
This method does the following (assuming !getAllowsInvalid()):
iterate over the max of the deleted region or the text length, for
each character:
- If it is valid (matches the mask at the particular position, or
matches the literal character at the position), allow it
- 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.
- Else if at the end of the inserted text, the replace the item with
the placeholder
- Otherwise the insert is bogus and false is returned.
|
public String getInvalidCharacters() {
return invalidCharacters;
}
Returns the characters that are not valid for input. |
public String getMask() {
return mask;
}
Returns the formatting mask. |
public String getPlaceholder() {
return placeholderString;
}
Returns the String to use if the value does not completely fill
in the mask. |
public char getPlaceholderCharacter() {
return placeholder;
}
Returns the character to use in place of characters that are not present
in the value, ie the user must fill them in. |
public String getValidCharacters() {
return validCharacters;
}
Returns the valid characters that can be input. |
public boolean getValueContainsLiteralCharacters() {
return containsLiteralChars;
}
Returns true if stringToValue should return literal
characters in the mask. |
public void install(JFormattedTextField ftf) {
super.install(ftf);
// valueToString doesn't throw, but stringToValue does, need to
// update the editValid state appropriately
if (ftf != null) {
Object value = ftf.getValue();
try {
stringToValue(valueToString(value));
} catch (ParseException pe) {
setEditValid(false);
}
}
}
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 Action s 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. |
boolean isNavigatable(int offset) {
if (!getAllowsInvalid()) {
return (offset < getMaxLength() && !isLiteral(offset));
}
return true;
}
Returns true if the MaskFormatter allows invalid, or
the offset is less than the max length and the character at
offset is a literal. |
boolean isValidEdit(ReplaceHolder rh) {
if (!getAllowsInvalid()) {
String newString = getReplaceString(rh.offset, rh.length, rh.text);
try {
rh.value = stringToValue(newString, false);
return true;
} catch (ParseException pe) {
return false;
}
}
return true;
}
|
public void setInvalidCharacters(String invalidCharacters) {
this.invalidCharacters = 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. |
public void setMask(String mask) throws ParseException {
this.mask = mask;
updateInternalMask();
}
Sets the mask dictating the legal characters.
This will throw a ParseException if mask is
not valid. |
public void setPlaceholder(String placeholder) {
this.placeholderString = 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. |
public void setPlaceholderCharacter(char placeholder) {
this.placeholder = 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. |
public void setValidCharacters(String validCharacters) {
this.validCharacters = 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. |
public void setValueContainsLiteralCharacters(boolean containsLiteralChars) {
this.containsLiteralChars = 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' . |
public Object stringToValue(String value) throws ParseException {
return stringToValue(value, true);
}
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 throw a
ParseException if the value does not match the current
mask. Refer to #setValueContainsLiteralCharacters for details
on how literals are treated. |
public String valueToString(Object value) throws ParseException {
String sValue = (value == null) ? "" : value.toString();
StringBuilder result = new StringBuilder();
String placeholder = getPlaceholder();
int[] valueCounter = { 0 };
append(result, sValue, valueCounter, placeholder, maskChars);
return result.toString();
}
|