|
Character.isDigit
.
* </tr>
* <tr>
* <td>'
* <td>Escape character, used to escape any of the
* special formatting characters.</td>
* </tr>
* <tr>
* <td>U
* </tr>
* <tr>
* </tr>
* <tr>
* <tr>
* </table>
*
* <p>
* 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.
* <p>
* You can further restrict the characters that can be input by the
* <code>setInvalidCharacters and setValidCharacters
* methods. <code>setInvalidCharacters allows you to specify
* which characters are not legal. <code>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:
* <pre>
* MaskFormatter formatter = new MaskFormatter("0x***");
* formatter.setValidCharacters("0123456789abcdefABCDEF");
* </pre>
* <p>
* 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:
* <pre>
* MaskFormatter formatter = new MaskFormatter("###-####");
* formatter.setPlaceholderCharacter('_');
* formatter.getDisplayValue(tf, "123");
* </pre>
* <p>
* Would result in the string '123-____'. If
* <code>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.
* <p>
* If a <code>MaskFormatter is configured to only allow valid characters
* (<code>setAllowsInvalid(false)) literal characters will be skipped as
* necessary when editing. Consider a <code>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):
* <pre>
* |555-1212
* 5|55-1212
* 55|5-1212
* 555-|1212
* 555-1|212
* </pre>
* The '-' is a literal (non-editable) character, and is skipped.
* <p>
* Similar behavior will result when editing. Consider inserting the string
* '123-45' and '12345' into the <code>MaskFormatter in the
* previous example. Both inserts will result in the same String,
* '123-45__'. When <code>MaskFormatter
* is processing the insert at character position 3 (the '-'), two things can
* happen:
* <ol>
* <li>If the inserted character is '-', it is accepted.
* <li>If the inserted character matches the mask for the next non-literal
* character, it is accepted at the new location.
* <li>Anything else results in an invalid edit
* </ol>
* <p>
* By default <code>MaskFormatter will not allow invalid edits, you can
* change this with the <code>setAllowsInvalid method, and will
* commit edits on valid edits (use the <code>setCommitsOnValidEdit to
* change this).
* <p>
* By default, <code>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 <code>setOverwriteMode.
* <p>
* <strong>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 JavaBeans™
* has been added to the <code>java.beans package.
* Please see {@link java.beans.XMLEncoder}.
*
* @since 1.4
*/
public class MaskFormatter extends DefaultFormatter {
// Potential values in mask.
private static final char DIGIT_KEY = '#';
private static final char LITERAL_KEY = '\'';
private static final char UPPERCASE_KEY = 'U';
private static final char LOWERCASE_KEY = 'L';
private static final char ALPHA_NUMERIC_KEY = 'A';
private static final char CHARACTER_KEY = '?';
private static final char ANYTHING_KEY = '*';
private static final char HEX_KEY = 'H';
private static final MaskCharacter[] EmptyMaskChars = new MaskCharacter[0];
/** The user specified mask. */
private String mask;
private transient MaskCharacter[] maskChars;
/** List of valid characters. */
private String validCharacters;
/** List of invalid characters. */
private String invalidCharacters;
/** String used for the passed in value if it does not completely
* fill the mask. */
private String placeholderString;
/** String used to represent characters not present. */
private char placeholder;
/** Indicates if the value contains the literal characters. */
private boolean containsLiteralChars;
/**
* Creates a MaskFormatter with no mask.
*/
public MaskFormatter() {
setAllowsInvalid(false);
containsLiteralChars = true;
maskChars = EmptyMaskChars;
placeholder = ' ';
}
/**
* Creates a <code>MaskFormatter with the specified mask.
* A <code>ParseException
* will be thrown if <code>mask is an invalid mask.
*
* @throws ParseException if mask does not contain valid mask characters
*/
public MaskFormatter(String mask) throws ParseException {
this();
setMask(mask);
}
/**
* Sets the mask dictating the legal characters.
* This will throw a <code>ParseException if mask
is
* not valid.
*
* @throws ParseException if mask does not contain valid mask characters
*/
public void setMask(String mask) throws ParseException {
this.mask = mask;
updateInternalMask();
}
/**
* Returns the formatting mask.
*
* @return Mask dictating legal character values.
*/
public String getMask() {
return mask;
}
/**
* Allows for further restricting of the characters that can be input.
* Only characters specified in the mask, not in the
* <code>invalidCharacters, and in
* <code>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.
*
* @param validCharacters If non-null, specifies legal characters.
*/
public void setValidCharacters(String validCharacters) {
this.validCharacters = validCharacters;
}
/**
* Returns the valid characters that can be input.
*
* @return Legal characters
*/
public String getValidCharacters() {
return validCharacters;
}
/**
* Allows for further restricting of the characters that can be input.
* Only characters specified in the mask, not in the
* <code>invalidCharacters, and in
* <code>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.
*
* @param invalidCharacters If non-null, specifies illegal characters.
*/
public void setInvalidCharacters(String invalidCharacters) {
this.invalidCharacters = invalidCharacters;
}
/**
* Returns the characters that are not valid for input.
*
* @return illegal characters.
*/
public String getInvalidCharacters() {
return invalidCharacters;
}
/**
* 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.
*
* @param placeholder String used when formatting if the value does not
* completely fill the mask
*/
public void setPlaceholder(String placeholder) {
this.placeholderString = placeholder;
}
/**
* Returns the String to use if the value does not completely fill
* in the mask.
*
* @return String used when formatting if the value does not
* completely fill the mask
*/
public String getPlaceholder() {
return placeholderString;
}
/**
* 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.
* <p>
* This is only applicable if the placeholder string has not been
* specified, or does not completely fill in the mask.
*
* @param placeholder Character used when formatting if the value does not
* completely fill the mask
*/
public void setPlaceholderCharacter(char placeholder) {
this.placeholder = placeholder;
}
/**
* Returns the character to use in place of characters that are not present
* in the value, ie the user must fill them in.
*
* @return Character used when formatting if the value does not
* completely fill the mask
*/
public char getPlaceholderCharacter() {
return placeholder;
}
/**
* If true, the returned value and set value will also contain the literal
* characters in mask.
* <p>
* For example, if the mask is <code>'(###) ###-####', the
* current value is <code>'(415) 555-1212', and
* <code>valueContainsLiteralCharacters is
* true <code>stringToValue will return
* <code>'(415) 555-1212'. On the other hand, if
* <code>valueContainsLiteralCharacters is false,
* <code>stringToValue will return '4155551212'
.
*
* @param containsLiteralChars Used to indicate if literal characters in
* mask should be returned in stringToValue
*/
public void setValueContainsLiteralCharacters(
boolean containsLiteralChars) {
this.containsLiteralChars = containsLiteralChars;
}
/**
* Returns true if <code>stringToValue should return literal
* characters in the mask.
*
* @return True if literal characters in mask should be returned in
* stringToValue
*/
public boolean getValueContainsLiteralCharacters() {
return containsLiteralChars;
}
/**
* Parses the text, returning the appropriate Object representation of
* the String <code>value. This strips the literal characters as
* necessary and invokes supers <code>stringToValue, so that if
* you have specified a value class (<code>setValueClass) an
* instance of it will be created. This will throw a
* <code>ParseException if the value does not match the current
* mask. Refer to {@link #setValueContainsLiteralCharacters} for details
* on how literals are treated.
*
* @throws ParseException if there is an error in the conversion
* @param value String to convert
* @see #setValueContainsLiteralCharacters
* @return Object representation of text
*/
public Object stringToValue(String value) throws ParseException {
return stringToValue(value, true);
}
/**
* Returns a String representation of the Object <code>value
* based on the mask. Refer to
* {@link #setValueContainsLiteralCharacters} for details
* on how literals are treated.
*
* @throws ParseException if there is an error in the conversion
* @param value Value to convert
* @see #setValueContainsLiteralCharacters
* @return String representation of value
*/
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();
}
/**
* Installs the <code>DefaultFormatter onto a particular
* <code>JFormattedTextField.
* This will invoke <code>valueToString to convert the
* current value from the <code>JFormattedTextField to
* a String. This will then install the <code>Actions from
* <code>getActions, the DocumentFilter
* returned from <code>getDocumentFilter and the
* <code>NavigationFilter returned from
* <code>getNavigationFilter onto the
* <code>JFormattedTextField.
* <p>
* Subclasses will typically only need to override this if they
* wish to install additional listeners on the
* <code>JFormattedTextField.
* <p>
* If there is a <code>ParseException in converting the
* current value to a String, this will set the text to an empty
* String, and mark the <code>JFormattedTextField as being
* in an invalid state.
* <p>
* While this is a public method, this is typically only useful
* for subclassers of <code>JFormattedTextField.
* <code>JFormattedTextField will invoke this method at
* the appropriate times when the value changes, or its internal
* state changes.
*
* @param ftf JFormattedTextField to format for, may be null indicating
* uninstall from current JFormattedTextField.
*/
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);
}
}
}
/**
* Actual <code>stringToValue implementation.
* If <code>completeMatch is true, the value must exactly match
* the mask, on the other hand if <code>completeMatch is false
* the string must match the mask or the placeholder string.
*/
private Object stringToValue(String value, boolean completeMatch) throws
ParseException {
int errorOffset;
if ((errorOffset = getInvalidOffset(value, completeMatch)) == -1) {
if (!getValueContainsLiteralCharacters()) {
value = stripLiteralChars(value);
}
return super.stringToValue(value);
}
throw new ParseException("stringToValue passed invalid value",
errorOffset);
}
/**
* Returns -1 if the passed in string is valid, otherwise the index of
* the first bogus character is returned.
*/
private int getInvalidOffset(String string, boolean completeMatch) {
int iLength = string.length();
if (iLength != getMaxLength()) {
// trivially false
return iLength;
}
for (int counter = 0, max = string.length(); counter < max; counter++){
char aChar = string.charAt(counter);
if (!isValidCharacter(counter, aChar) &&
(completeMatch || !isPlaceholder(counter, aChar))) {
return counter;
}
}
return -1;
}
/**
* Invokes <code>append on the mask characters in
* <code>mask.
*/
private void append(StringBuilder result, String value, int[] index,
String placeholder, MaskCharacter[] mask)
throws ParseException {
for (int counter = 0, maxCounter = mask.length;
counter < maxCounter; counter++) {
mask[counter].append(result, value, index, placeholder);
}
}
/**
* Updates the internal representation of the mask.
*/
private void updateInternalMask() throws ParseException {
String mask = getMask();
ArrayList<MaskCharacter> fixed = new ArrayListbuff
.
*/
public void append(StringBuilder buff, String formatting, int[] index,
String placeholder)
throws ParseException {
boolean inString = index[0] < formatting.length();
char aChar = inString ? formatting.charAt(index[0]) : 0;
if (isLiteral()) {
buff.append(getChar(aChar));
if (getValueContainsLiteralCharacters()) {
if (inString && aChar != getChar(aChar)) {
throw new ParseException("Invalid character: " +
aChar, index[0]);
}
index[0] = index[0] + 1;
}
}
else if (index[0] >= formatting.length()) {
if (placeholder != null && index[0] < placeholder.length()) {
buff.append(placeholder.charAt(index[0]));
}
else {
buff.append(getPlaceholderCharacter());
}
index[0] = index[0] + 1;
}
else if (isValidCharacter(aChar)) {
buff.append(getChar(aChar));
index[0] = index[0] + 1;
}
else {
throw new ParseException("Invalid character: " + aChar,
index[0]);
}
}
}
/**
* Used to represent a fixed character in the mask.
*/
private class LiteralCharacter extends MaskCharacter {
private char fixedChar;
public LiteralCharacter(char fixedChar) {
this.fixedChar = fixedChar;
}
public boolean isLiteral() {
return true;
}
public char getChar(char aChar) {
return fixedChar;
}
}
/**
* Represents a number, uses <code>Character.isDigit.
*/
private class DigitMaskCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return (Character.isDigit(aChar) &&
super.isValidCharacter(aChar));
}
}
/**
* Represents a character, lower case letters are mapped to upper case
* using <code>Character.toUpperCase.
*/
private class UpperCaseCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return (Character.isLetter(aChar) &&
super.isValidCharacter(aChar));
}
public char getChar(char aChar) {
return Character.toUpperCase(aChar);
}
}
/**
* Represents a character, upper case letters are mapped to lower case
* using <code>Character.toLowerCase.
*/
private class LowerCaseCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return (Character.isLetter(aChar) &&
super.isValidCharacter(aChar));
}
public char getChar(char aChar) {
return Character.toLowerCase(aChar);
}
}
/**
* Represents either a character or digit, uses
* <code>Character.isLetterOrDigit.
*/
private class AlphaNumericCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return (Character.isLetterOrDigit(aChar) &&
super.isValidCharacter(aChar));
}
}
/**
* Represents a letter, uses <code>Character.isLetter.
*/
private class CharCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return (Character.isLetter(aChar) &&
super.isValidCharacter(aChar));
}
}
/**
* Represents a hex character, 0-9a-fA-F. a-f is mapped to A-F
*/
private class HexCharacter extends MaskCharacter {
public boolean isValidCharacter(char aChar) {
return ((aChar == '0' || aChar == '1' ||
aChar == '2' || aChar == '3' ||
aChar == '4' || aChar == '5' ||
aChar == '6' || aChar == '7' ||
aChar == '8' || aChar == '9' ||
aChar == 'a' || aChar == 'A' ||
aChar == 'b' || aChar == 'B' ||
aChar == 'c' || aChar == 'C' ||
aChar == 'd' || aChar == 'D' ||
aChar == 'e' || aChar == 'E' ||
aChar == 'f' || aChar == 'F') &&
super.isValidCharacter(aChar));
}
public char getChar(char aChar) {
if (Character.isDigit(aChar)) {
return aChar;
}
return Character.toUpperCase(aChar);
}
}
}
Here is a short list of links related to this Java MaskFormatter.java source code file:
Java example source code file (MaskFormatter.java)
The MaskFormatter.java Java example source code/* * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing.text; import java.io.*; import java.text.*; import java.util.*; import javax.swing.*; /** * <code>MaskFormatter is used to format and edit strings. The behavior * of a <code>MaskFormatter is controlled by way of a String mask * that specifies the valid characters that can be contained at a particular * location in the <code>Document model. The following characters can * be specified: * * <table border=1 summary="Valid characters and their descriptions"> * <tr> * <th>Character * <th> | Any character (Character.isLetter ). All
* lowercase letters are mapped to upper case.</td>
* </tr>
* <tr> | L | Any character (Character.isLetter ). All
* upper case letters are mapped to lower case.</td>
* </tr>
* <tr> | A | Any character or number (Character.isLetter
* or <code>Character.isDigit) | ? | Any character * (<code>Character.isLetter). | * | Anything. | |
H | Any hex character (0-9, a-f or A-F). |
... this post is sponsored by my books ... | |
![]() #1 New Release! |
![]() FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.