KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > text > MaskFormatter


1 /*
2  * @(#)MaskFormatter.java 1.12 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package javax.swing.text;
9
10 import java.io.*;
11 import java.text.*;
12 import java.util.*;
13 import javax.swing.*;
14 import javax.swing.text.*;
15
16 /**
17  * <code>MaskFormatter</code> is used to format and edit strings. The behavior
18  * of a <code>MaskFormatter</code> is controlled by way of a String mask
19  * that specifies the valid characters that can be contained at a particular
20  * location in the <code>Document</code> model. The following characters can
21  * be specified:
22  *
23  * <table border=1 summary="Valid characters and their descriptions">
24  * <tr>
25  * <th>Character&nbsp;</th>
26  * <th><p align="left">Description</p></th>
27  * </tr>
28  * <tr>
29  * <td>#</td>
30  * <td>Any valid number, uses <code>Character.isDigit</code>.</td>
31  * </tr>
32  * <tr>
33  * <td>'</td>
34  * <td>Escape character, used to escape any of the
35  * special formatting characters.</td>
36  * </tr>
37  * <tr>
38  * <td>U</td><td>Any character (<code>Character.isLetter</code>). All
39  * lowercase letters are mapped to upper case.</td>
40  * </tr>
41  * <tr><td>L</td><td>Any character (<code>Character.isLetter</code>). All
42  * upper case letters are mapped to lower case.</td>
43  * </tr>
44  * <tr><td>A</td><td>Any character or number (<code>Character.isLetter</code>
45  * or <code>Character.isDigit</code>)</td>
46  * </tr>
47  * <tr><td>?</td><td>Any character
48  * (<code>Character.isLetter</code>).</td>
49  * </tr>
50  * <tr><td>*</td><td>Anything.</td></tr>
51  * <tr><td>H</td><td>Any hex character (0-9, a-f or A-F).</td></tr>
52  * </table>
53  *
54  * <p>
55  * Typically characters correspond to one char, but in certain languages this
56  * is not the case. The mask is on a per character basis, and will thus
57  * adjust to fit as many chars as are needed.
58  * <p>
59  * You can further restrict the characters that can be input by the
60  * <code>setInvalidCharacters</code> and <code>setValidCharacters</code>
61  * methods. <code>setInvalidCharacters</code> allows you to specify
62  * which characters are not legal. <code>setValidCharacters</code> allows
63  * you to specify which characters are valid. For example, the following
64  * code block is equivalent to a mask of '0xHHH' with no invalid/valid
65  * characters:
66  * <pre>
67  * MaskFormatter formatter = new MaskFormatter("0x***");
68  * formatter.setValidCharacters("0123456789abcdefABCDEF");
69  * </pre>
70  * <p>
71  * When initially formatting a value if the length of the string is
72  * less than the length of the mask, two things can happen. Either
73  * the placeholder string will be used, or the placeholder character will
74  * be used. Precedence is given to the placeholder string. For example:
75  * <pre>
76  * MaskFormatter formatter = new MaskFormatter("###-####");
77  * formatter.setPlaceholderCharacter('_');
78  * formatter.getDisplayValue(tf, "123");
79  * </pre>
80  * <p>
81  * Would result in the string '123-____'. If
82  * <code>setPlaceholder("555-1212")</code> was invoked '123-1212' would
83  * result. The placeholder String is only used on the initial format,
84  * on subsequent formats only the placeholder character will be used.
85  * <p>
86  * If a <code>MaskFormatter</code> is configured to only allow valid characters
87  * (<code>setAllowsInvalid(false)</code>) literal characters will be skipped as
88  * necessary when editing. Consider a <code>MaskFormatter</code> with
89  * the mask "###-####" and current value "555-1212". Using the right
90  * arrow key to navigate through the field will result in (| indicates the
91  * position of the caret):
92  * <pre>
93  * |555-1212
94  * 5|55-1212
95  * 55|5-1212
96  * 555-|1212
97  * 555-1|212
98  * </pre>
99  * The '-' is a literal (non-editable) character, and is skipped.
100  * <p>
101  * Similar behavior will result when editing. Consider inserting the string
102  * '123-45' and '12345' into the <code>MaskFormatter</code> in the
103  * previous example. Both inserts will result in the same String,
104  * '123-45__'. When <code>MaskFormatter</code>
105  * is processing the insert at character position 3 (the '-'), two things can
106  * happen:
107  * <ol>
108  * <li>If the inserted character is '-', it is accepted.
109  * <li>If the inserted character matches the mask for the next non-literal
110  * character, it is accepted at the new location.
111  * <li>Anything else results in an invalid edit
112  * </ol>
113  * <p>
114  * By default <code>MaskFormatter</code> will not allow invalid edits, you can
115  * change this with the <code>setAllowsInvalid</code> method, and will
116  * commit edits on valid edits (use the <code>setCommitsOnValidEdit</code> to
117  * change this).
118  * <p>
119  * By default, <code>MaskFormatter</code> is in overwrite mode. That is as
120  * characters are typed a new character is not inserted, rather the character
121  * at the current location is replaced with the newly typed character. You
122  * can change this behavior by way of the method <code>setOverwriteMode</code>.
123  * <p>
124  * <strong>Warning:</strong>
125  * Serialized objects of this class will not be compatible with
126  * future Swing releases. The current serialization support is
127  * appropriate for short term storage or RMI between applications running
128  * the same version of Swing. As of 1.4, support for long term storage
129  * of all JavaBeans<sup><font size="-2">TM</font></sup>
130  * has been added to the <code>java.beans</code> package.
131  * Please see {@link java.beans.XMLEncoder}.
132  *
133  * @version 1.12 12/19/03
134  * @since 1.4
135  */

136 public class MaskFormatter extends DefaultFormatter JavaDoc {
137     // Potential values in mask.
138
private static final char DIGIT_KEY = '#';
139     private static final char LITERAL_KEY = '\'';
140     private static final char UPPERCASE_KEY = 'U';
141     private static final char LOWERCASE_KEY = 'L';
142     private static final char ALPHA_NUMERIC_KEY = 'A';
143     private static final char CHARACTER_KEY = '?';
144     private static final char ANYTHING_KEY = '*';
145     private static final char HEX_KEY = 'H';
146
147     private static final MaskCharacter[] EmptyMaskChars = new MaskCharacter[0];
148
149     /** The user specified mask. */
150     private String JavaDoc mask;
151
152     private transient MaskCharacter[] maskChars;
153
154     /** List of valid characters. */
155     private String JavaDoc validCharacters;
156
157     /** List of invalid characters. */
158     private String JavaDoc invalidCharacters;
159
160     /** String used for the passed in value if it does not completely
161      * fill the mask. */

162     private String JavaDoc placeholderString;
163
164     /** String used to represent characters not present. */
165     private char placeholder;
166
167     /** Indicates if the value contains the literal characters. */
168     private boolean containsLiteralChars;
169
170
171     /**
172      * Creates a MaskFormatter with no mask.
173      */

174     public MaskFormatter() {
175         setAllowsInvalid(false);
176         containsLiteralChars = true;
177         maskChars = EmptyMaskChars;
178         placeholder = ' ';
179     }
180
181     /**
182      * Creates a <code>MaskFormatter</code> with the specified mask.
183      * A <code>ParseException</code>
184      * will be thrown if <code>mask</code> is an invalid mask.
185      *
186      * @throws ParseException if mask does not contain valid mask characters
187      */

188     public MaskFormatter(String JavaDoc mask) throws ParseException {
189         this();
190         setMask(mask);
191     }
192
193     /**
194      * Sets the mask dictating the legal characters.
195      * This will throw a <code>ParseException</code> if <code>mask</code> is
196      * not valid.
197      *
198      * @throws ParseException if mask does not contain valid mask characters
199      */

200     public void setMask(String JavaDoc mask) throws ParseException {
201         this.mask = mask;
202         updateInternalMask();
203     }
204
205     /**
206      * Returns the formatting mask.
207      *
208      * @return Mask dictating legal character values.
209      */

210     public String JavaDoc getMask() {
211         return mask;
212     }
213
214     /**
215      * Allows for further restricting of the characters that can be input.
216      * Only characters specified in the mask, not in the
217      * <code>invalidCharacters</code>, and in
218      * <code>validCharacters</code> will be allowed to be input. Passing
219      * in null (the default) implies the valid characters are only bound
220      * by the mask and the invalid characters.
221      *
222      * @param validCharacters If non-null, specifies legal characters.
223      */

224     public void setValidCharacters(String JavaDoc validCharacters) {
225         this.validCharacters = validCharacters;
226     }
227
228     /**
229      * Returns the valid characters that can be input.
230      *
231      * @return Legal characters
232      */

233     public String JavaDoc getValidCharacters() {
234         return validCharacters;
235     }
236
237     /**
238      * Allows for further restricting of the characters that can be input.
239      * Only characters specified in the mask, not in the
240      * <code>invalidCharacters</code>, and in
241      * <code>validCharacters</code> will be allowed to be input. Passing
242      * in null (the default) implies the valid characters are only bound
243      * by the mask and the valid characters.
244      *
245      * @param invalidCharacters If non-null, specifies illegal characters.
246      */

247     public void setInvalidCharacters(String JavaDoc invalidCharacters) {
248         this.invalidCharacters = invalidCharacters;
249     }
250
251     /**
252      * Returns the characters that are not valid for input.
253      *
254      * @return illegal characters.
255      */

256     public String JavaDoc getInvalidCharacters() {
257         return invalidCharacters;
258     }
259
260     /**
261      * Sets the string to use if the value does not completely fill in
262      * the mask. A null value implies the placeholder char should be used.
263      *
264      * @param placeholder String used when formatting if the value does not
265      * completely fill the mask
266      */

267     public void setPlaceholder(String JavaDoc placeholder) {
268         this.placeholderString = placeholder;
269     }
270
271     /**
272      * Returns the String to use if the value does not completely fill
273      * in the mask.
274      *
275      * @return String used when formatting if the value does not
276      * completely fill the mask
277      */

278     public String JavaDoc getPlaceholder() {
279         return placeholderString;
280     }
281
282     /**
283      * Sets the character to use in place of characters that are not present
284      * in the value, ie the user must fill them in. The default value is
285      * a space.
286      * <p>
287      * This is only applicable if the placeholder string has not been
288      * specified, or does not completely fill in the mask.
289      *
290      * @param placeholder Character used when formatting if the value does not
291      * completely fill the mask
292      */

293     public void setPlaceholderCharacter(char placeholder) {
294         this.placeholder = placeholder;
295     }
296
297     /**
298      * Returns the character to use in place of characters that are not present
299      * in the value, ie the user must fill them in.
300      *
301      * @return Character used when formatting if the value does not
302      * completely fill the mask
303      */

304     public char getPlaceholderCharacter() {
305         return placeholder;
306     }
307
308     /**
309      * If true, the returned value and set value will also contain the literal
310      * characters in mask.
311      * <p>
312      * For example, if the mask is <code>'(###) ###-####'</code>, the
313      * current value is <code>'(415) 555-1212'</code>, and
314      * <code>valueContainsLiteralCharacters</code> is
315      * true <code>stringToValue</code> will return
316      * <code>'(415) 555-1212'</code>. On the other hand, if
317      * <code>valueContainsLiteralCharacters</code> is false,
318      * <code>stringToValue</code> will return <code>'4155551212'</code>.
319      *
320      * @param containsLiteralChars Used to indicate if literal characters in
321      * mask should be returned in stringToValue
322      */

323     public void setValueContainsLiteralCharacters(
324                         boolean containsLiteralChars) {
325         this.containsLiteralChars = containsLiteralChars;
326     }
327
328     /**
329      * Returns true if <code>stringToValue</code> should return literal
330      * characters in the mask.
331      *
332      * @return True if literal characters in mask should be returned in
333      * stringToValue
334      */

335     public boolean getValueContainsLiteralCharacters() {
336         return containsLiteralChars;
337     }
338
339     /**
340      * Parses the text, returning the appropriate Object representation of
341      * the String <code>value</code>. This strips the literal characters as
342      * necessary and invokes supers <code>stringToValue</code>, so that if
343      * you have specified a value class (<code>setValueClass</code>) an
344      * instance of it will be created. This will throw a
345      * <code>ParseException</code> if the value does not match the current
346      * mask. Refer to {@link #setValueContainsLiteralCharacters} for details
347      * on how literals are treated.
348      *
349      * @throws ParseException if there is an error in the conversion
350      * @param value String to convert
351      * @see #setValueContainsLiteralCharacters
352      * @return Object representation of text
353      */

354     public Object JavaDoc stringToValue(String JavaDoc value) throws ParseException {
355         return stringToValue(value, true);
356     }
357
358     /**
359      * Returns a String representation of the Object <code>value</code>
360      * based on the mask. Refer to
361      * {@link #setValueContainsLiteralCharacters} for details
362      * on how literals are treated.
363      *
364      * @throws ParseException if there is an error in the conversion
365      * @param value Value to convert
366      * @see #setValueContainsLiteralCharacters
367      * @return String representation of value
368      */

369     public String JavaDoc valueToString(Object JavaDoc value) throws ParseException {
370         String JavaDoc sValue = (value == null) ? "" : value.toString();
371         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
372         String JavaDoc placeholder = getPlaceholder();
373         int[] valueCounter = { 0 };
374
375         append(result, sValue, valueCounter, placeholder, maskChars);
376         return result.toString();
377     }
378
379     /**
380      * Installs the <code>DefaultFormatter</code> onto a particular
381      * <code>JFormattedTextField</code>.
382      * This will invoke <code>valueToString</code> to convert the
383      * current value from the <code>JFormattedTextField</code> to
384      * a String. This will then install the <code>Action</code>s from
385      * <code>getActions</code>, the <code>DocumentFilter</code>
386      * returned from <code>getDocumentFilter</code> and the
387      * <code>NavigationFilter</code> returned from
388      * <code>getNavigationFilter</code> onto the
389      * <code>JFormattedTextField</code>.
390      * <p>
391      * Subclasses will typically only need to override this if they
392      * wish to install additional listeners on the
393      * <code>JFormattedTextField</code>.
394      * <p>
395      * If there is a <code>ParseException</code> in converting the
396      * current value to a String, this will set the text to an empty
397      * String, and mark the <code>JFormattedTextField</code> as being
398      * in an invalid state.
399      * <p>
400      * While this is a public method, this is typically only useful
401      * for subclassers of <code>JFormattedTextField</code>.
402      * <code>JFormattedTextField</code> will invoke this method at
403      * the appropriate times when the value changes, or its internal
404      * state changes.
405      *
406      * @param ftf JFormattedTextField to format for, may be null indicating
407      * uninstall from current JFormattedTextField.
408      */

409     public void install(JFormattedTextField ftf) {
410         super.install(ftf);
411         // valueToString doesn't throw, but stringToValue does, need to
412
// update the editValid state appropriately
413
if (ftf != null) {
414             Object JavaDoc value = ftf.getValue();
415
416             try {
417                 stringToValue(valueToString(value));
418             } catch (ParseException pe) {
419                 setEditValid(false);
420             }
421         }
422     }
423
424     /**
425      * Actual <code>stringToValue</code> implementation.
426      * If <code>completeMatch</code> is true, the value must exactly match
427      * the mask, on the other hand if <code>completeMatch</code> is false
428      * the string must match the mask or the placeholder string.
429      */

430     private Object JavaDoc stringToValue(String JavaDoc value, boolean completeMatch) throws
431                          ParseException {
432         int errorOffset = -1;
433
434         if ((errorOffset = getInvalidOffset(value, completeMatch)) == -1) {
435             if (!getValueContainsLiteralCharacters()) {
436                 value = stripLiteralChars(value);
437             }
438             return super.stringToValue(value);
439         }
440         throw new ParseException("stringToValue passed invalid value",
441                                  errorOffset);
442     }
443
444     /**
445      * Returns -1 if the passed in string is valid, otherwise the index of
446      * the first bogus character is returned.
447      */

448     private int getInvalidOffset(String JavaDoc string, boolean completeMatch) {
449         int iLength = string.length();
450
451         if (iLength != getMaxLength()) {
452             // trivially false
453
return iLength;
454         }
455         for (int counter = 0, max = string.length(); counter < max; counter++){
456             char aChar = string.charAt(counter);
457
458             if (!isValidCharacter(counter, aChar) &&
459                 (completeMatch || !isPlaceholder(counter, aChar))) {
460                 return counter;
461             }
462         }
463         return -1;
464     }
465
466     /**
467      * Invokes <code>append</code> on the mask characters in
468      * <code>mask</code>.
469      */

470     private void append(StringBuffer JavaDoc result, String JavaDoc value, int[] index,
471                         String JavaDoc placeholder, MaskCharacter[] mask)
472                           throws ParseException {
473         for (int counter = 0, maxCounter = mask.length;
474              counter < maxCounter; counter++) {
475             mask[counter].append(result, value, index, placeholder);
476         }
477     }
478
479     /**
480      * Updates the internal representation of the mask.
481      */

482     private void updateInternalMask() throws ParseException {
483         String JavaDoc mask = getMask();
484         ArrayList fixed = new ArrayList();
485         ArrayList temp = fixed;
486
487         if (mask != null) {
488             for (int counter = 0, maxCounter = mask.length();
489                  counter < maxCounter; counter++) {
490                 char maskChar = mask.charAt(counter);
491
492                 switch (maskChar) {
493                 case DIGIT_KEY:
494                     temp.add(new DigitMaskCharacter());
495                     break;
496                 case LITERAL_KEY:
497                     if (++counter < maxCounter) {
498                         maskChar = mask.charAt(counter);
499                         temp.add(new LiteralCharacter(maskChar));
500                     }
501                     // else: Could actually throw if else
502
break;
503                 case UPPERCASE_KEY:
504                     temp.add(new UpperCaseCharacter());
505                     break;
506                 case LOWERCASE_KEY:
507                     temp.add(new LowerCaseCharacter());
508                     break;
509                 case ALPHA_NUMERIC_KEY:
510                     temp.add(new AlphaNumericCharacter());
511                     break;
512                 case CHARACTER_KEY:
513                     temp.add(new CharCharacter());
514                     break;
515                 case ANYTHING_KEY:
516                     temp.add(new MaskCharacter());
517                     break;
518                 case HEX_KEY:
519                     temp.add(new HexCharacter());
520                     break;
521                 default:
522                     temp.add(new LiteralCharacter(maskChar));
523                     break;
524                 }
525             }
526         }
527         if (fixed.size() == 0) {
528             maskChars = EmptyMaskChars;
529         }
530         else {
531             maskChars = new MaskCharacter[fixed.size()];
532             fixed.toArray(maskChars);
533         }
534     }
535
536     /**
537      * Returns the MaskCharacter at the specified location.
538      */

539     private MaskCharacter getMaskCharacter(int index) {
540         if (index >= maskChars.length) {
541             return null;
542         }
543         return maskChars[index];
544     }
545
546     /**
547      * Returns true if the placeholder character matches aChar.
548      */

549     private boolean isPlaceholder(int index, char aChar) {
550         return (getPlaceholderCharacter() == aChar);
551     }
552
553     /**
554      * Returns true if the passed in character matches the mask at the
555      * specified location.
556      */

557     private boolean isValidCharacter(int index, char aChar) {
558         return getMaskCharacter(index).isValidCharacter(aChar);
559     }
560
561     /**
562      * Returns true if the character at the specified location is a literal,
563      * that is it can not be edited.
564      */

565     private boolean isLiteral(int index) {
566         return getMaskCharacter(index).isLiteral();
567     }
568
569     /**
570      * Returns the maximum length the text can be.
571      */

572     private int getMaxLength() {
573         return maskChars.length;
574     }
575
576     /**
577      * Returns the literal character at the specified location.
578      */

579     private char getLiteral(int index) {
580         return getMaskCharacter(index).getChar((char)0);
581     }
582
583     /**
584      * Returns the character to insert at the specified location based on
585      * the passed in character. This provides a way to map certain sets
586      * of characters to alternative values (lowercase to
587      * uppercase...).
588      */

589     private char getCharacter(int index, char aChar) {
590         return getMaskCharacter(index).getChar(aChar);
591     }
592
593     /**
594      * Removes the literal characters from the passed in string.
595      */

596     private String JavaDoc stripLiteralChars(String JavaDoc string) {
597         StringBuffer JavaDoc sb = null;
598         int last = 0;
599
600         for (int counter = 0, max = string.length(); counter < max; counter++){
601             if (isLiteral(counter)) {
602                 if (sb == null) {
603                     sb = new StringBuffer JavaDoc();
604                     if (counter > 0) {
605                         sb.append(string.substring(0, counter));
606                     }
607                     last = counter + 1;
608                 }
609                 else if (last != counter) {
610                     sb.append(string.substring(last, counter));
611                 }
612                 last = counter + 1;
613             }
614         }
615         if (sb == null) {
616             // Assume the mask isn't all literals.
617
return string;
618         }
619         else if (last != string.length()) {
620             if (sb == null) {
621                 return string.substring(last);
622             }
623             sb.append(string.substring(last));
624         }
625         return sb.toString();
626     }
627
628
629     /**
630      * Subclassed to update the internal representation of the mask after
631      * the default read operation has completed.
632      */

633     private void readObject(ObjectInputStream s)
634         throws IOException, ClassNotFoundException JavaDoc {
635         s.defaultReadObject();
636         try {
637             updateInternalMask();
638         } catch (ParseException pe) {
639             // assert();
640
}
641     }
642
643     /**
644      * Returns true if the MaskFormatter allows invalid, or
645      * the offset is less than the max length and the character at
646      * <code>offset</code> is a literal.
647      */

648     boolean isNavigatable(int offset) {
649         if (!getAllowsInvalid()) {
650             return (offset < getMaxLength() && !isLiteral(offset));
651         }
652         return true;
653     }
654
655     /*
656      * Returns true if the operation described by <code>rh</code> will
657      * result in a legal edit. This may set the <code>value</code>
658      * field of <code>rh</code>.
659      * <p>
660      * This is overriden to return true for a partial match.
661      */

662     boolean isValidEdit(ReplaceHolder rh) {
663         if (!getAllowsInvalid()) {
664             String JavaDoc newString = getReplaceString(rh.offset, rh.length, rh.text);
665
666             try {
667                 rh.value = stringToValue(newString, false);
668
669                 return true;
670             } catch (ParseException pe) {
671                 return false;
672             }
673         }
674         return true;
675     }
676
677     /**
678      * This method does the following (assuming !getAllowsInvalid()):
679      * iterate over the max of the deleted region or the text length, for
680      * each character:
681      * <ol>
682      * <li>If it is valid (matches the mask at the particular position, or
683      * matches the literal character at the position), allow it
684      * <li>Else if the position identifies a literal character, add it. This
685      * allows for the user to paste in text that may/may not contain
686      * the literals. For example, in pasing in 5551212 into ###-####
687      * when the 1 is evaluated it is illegal (by the first test), but there
688      * is a literal at this position (-), so it is used. NOTE: This has
689      * a problem that you can't tell (without looking ahead) if you should
690      * eat literals in the text. For example, if you paste '555' into
691      * #5##, should it result in '5555' or '555 '? The current code will
692      * result in the latter, which feels a little better as selecting
693      * text than pasting will always result in the same thing.
694      * <li>Else if at the end of the inserted text, the replace the item with
695      * the placeholder
696      * <li>Otherwise the insert is bogus and false is returned.
697      * </ol>
698      */

699     boolean canReplace(ReplaceHolder rh) {
700         // This method is rather long, but much of the burden is in
701
// maintaining a String and swapping to a StringBuffer only if
702
// absolutely necessary.
703
if (!getAllowsInvalid()) {
704             StringBuffer JavaDoc replace = null;
705             String JavaDoc text = rh.text;
706             int tl = (text != null) ? text.length() : 0;
707
708             if (tl == 0 && rh.length == 1 && getFormattedTextField().
709                               getSelectionStart() != rh.offset) {
710                 // Backspace, adjust to actually delete next non-literal.
711
while (rh.offset > 0 && isLiteral(rh.offset)) {
712                     rh.offset--;
713                 }
714             }
715             int max = Math.min(getMaxLength() - rh.offset,
716                                Math.max(tl, rh.length));
717             for (int counter = 0, textIndex = 0; counter < max; counter++) {
718                 if (textIndex < tl && isValidCharacter(rh.offset + counter,
719                                                    text.charAt(textIndex))) {
720                     char aChar = text.charAt(textIndex);
721                     if (aChar != getCharacter(rh.offset + counter, aChar)) {
722                         if (replace == null) {
723                             replace = new StringBuffer JavaDoc();
724                             if (textIndex > 0) {
725                                 replace.append(text.substring(0, textIndex));
726                             }
727                         }
728                     }
729                     if (replace != null) {
730                         replace.append(getCharacter(rh.offset + counter,
731                                                     aChar));
732                     }
733                     textIndex++;
734                 }
735                 else if (isLiteral(rh.offset + counter)) {
736                     if (replace != null) {
737                         replace.append(getLiteral(rh.offset + counter));
738                         if (textIndex < tl) {
739                             max = Math.min(max + 1, getMaxLength() -
740                                            rh.offset);
741                         }
742                     }
743                     else if (textIndex > 0) {
744                         replace = new StringBuffer JavaDoc(max);
745                         replace.append(text.substring(0, textIndex));
746                         replace.append(getLiteral(rh.offset + counter));
747                         if (textIndex < tl) {
748                             // Evaluate the character in text again.
749
max = Math.min(max + 1, getMaxLength() -
750                                            rh.offset);
751                         }
752                         else if (rh.cursorPosition == -1) {
753                             rh.cursorPosition = rh.offset + counter;
754                         }
755                     }
756                     else {
757                         rh.offset++;
758                         rh.length--;
759                         counter--;
760             max--;
761                     }
762                 }
763                 else if (textIndex >= tl) {
764                     // placeholder
765
if (replace == null) {
766                         replace = new StringBuffer JavaDoc();
767                         if (text != null) {
768                             replace.append(text);
769                         }
770                     }
771                     replace.append(getPlaceholderCharacter());
772                     if (tl > 0 && rh.cursorPosition == -1) {
773                         rh.cursorPosition = rh.offset + counter;
774                     }
775                 }
776                 else {
777                     // Bogus character.
778
return false;
779                 }
780             }
781             if (replace != null) {
782                 rh.text = replace.toString();
783             }
784             else if (text != null && rh.offset + tl > getMaxLength()) {
785                 rh.text = text.substring(0, getMaxLength() - rh.offset);
786             }
787             if (getOverwriteMode() && rh.text != null) {
788                 rh.length = rh.text.length();
789             }
790         }
791         return super.canReplace(rh);
792     }
793
794
795     //
796
// Interal classes used to represent the mask.
797
//
798
private class MaskCharacter {
799         /**
800          * Subclasses should override this returning true if the instance
801          * represents a literal character. The default implementation
802          * returns false.
803          */

804         public boolean isLiteral() {
805             return false;
806         }
807
808         /**
809          * Returns true if <code>aChar</code> is a valid reprensentation of
810          * the receiver. The default implementation returns true if the
811          * receiver represents a literal character and <code>getChar</code>
812          * == aChar. Otherwise, this will return true is <code>aChar</code>
813          * is contained in the valid characters and not contained
814          * in the invalid characters.
815          */

816         public boolean isValidCharacter(char aChar) {
817             if (isLiteral()) {
818                 return (getChar(aChar) == aChar);
819             }
820
821             aChar = getChar(aChar);
822
823             String JavaDoc filter = getValidCharacters();
824
825             if (filter != null && filter.indexOf(aChar) == -1) {
826                 return false;
827             }
828             filter = getInvalidCharacters();
829             if (filter != null && filter.indexOf(aChar) != -1) {
830                 return false;
831             }
832             return true;
833         }
834
835         /**
836          * Returns the character to insert for <code>aChar</code>. The
837          * default implementation returns <code>aChar</code>. Subclasses
838          * that wish to do some sort of mapping, perhaps lower case to upper
839          * case should override this and do the necessary mapping.
840          */

841         public char getChar(char aChar) {
842             return aChar;
843         }
844
845         /**
846          * Appends the necessary character in <code>formatting</code> at
847          * <code>index</code> to <code>buff</code>.
848          */

849         public void append(StringBuffer JavaDoc buff, String JavaDoc formatting, int[] index,
850                            String JavaDoc placeholder)
851                           throws ParseException {
852             boolean inString = index[0] < formatting.length();
853             char aChar = inString ? formatting.charAt(index[0]) : 0;
854
855             if (isLiteral()) {
856                 buff.append(getChar(aChar));
857                 if (getValueContainsLiteralCharacters()) {
858                     if (inString && aChar != getChar(aChar)) {
859                         throw new ParseException("Invalid character: " +
860                                                  aChar, index[0]);
861                     }
862                     index[0] = index[0] + 1;
863                 }
864             }
865             else if (index[0] >= formatting.length()) {
866                 if (placeholder != null && index[0] < placeholder.length()) {
867                     buff.append(placeholder.charAt(index[0]));
868                 }
869                 else {
870                     buff.append(getPlaceholderCharacter());
871                 }
872                 index[0] = index[0] + 1;
873             }
874             else if (isValidCharacter(aChar)) {
875                 buff.append(getChar(aChar));
876                 index[0] = index[0] + 1;
877             }
878             else {
879                 throw new ParseException("Invalid character: " + aChar,
880                                          index[0]);
881             }
882         }
883     }
884
885
886     /**
887      * Used to represent a fixed character in the mask.
888      */

889     private class LiteralCharacter extends MaskCharacter {
890         private char fixedChar;
891
892         public LiteralCharacter(char fixedChar) {
893             this.fixedChar = fixedChar;
894         }
895
896         public boolean isLiteral() {
897             return true;
898         }
899
900         public char getChar(char aChar) {
901             return fixedChar;
902         }
903     }
904
905
906     /**
907      * Represents a number, uses <code>Character.isDigit</code>.
908      */

909     private class DigitMaskCharacter extends MaskCharacter {
910         public boolean isValidCharacter(char aChar) {
911             return (Character.isDigit(aChar) &&
912                     super.isValidCharacter(aChar));
913         }
914     }
915
916
917     /**
918      * Represents a character, lower case letters are mapped to upper case
919      * using <code>Character.toUpperCase</code>.
920      */

921     private class UpperCaseCharacter extends MaskCharacter {
922         public boolean isValidCharacter(char aChar) {
923             return (Character.isLetter(aChar) &&
924                      super.isValidCharacter(aChar));
925         }
926
927         public char getChar(char aChar) {
928             return Character.toUpperCase(aChar);
929         }
930     }
931
932
933     /**
934      * Represents a character, upper case letters are mapped to lower case
935      * using <code>Character.toLowerCase</code>.
936      */

937     private class LowerCaseCharacter extends MaskCharacter {
938         public boolean isValidCharacter(char aChar) {
939             return (Character.isLetter(aChar) &&
940                      super.isValidCharacter(aChar));
941         }
942
943         public char getChar(char aChar) {
944             return Character.toLowerCase(aChar);
945         }
946     }
947
948
949     /**
950      * Represents either a character or digit, uses
951      * <code>Character.isLetterOrDigit</code>.
952      */

953     private class AlphaNumericCharacter extends MaskCharacter {
954         public boolean isValidCharacter(char aChar) {
955             return (Character.isLetterOrDigit(aChar) &&
956                      super.isValidCharacter(aChar));
957         }
958     }
959
960
961     /**
962      * Represents a letter, uses <code>Character.isLetter</code>.
963      */

964     private class CharCharacter extends MaskCharacter {
965         public boolean isValidCharacter(char aChar) {
966             return (Character.isLetter(aChar) &&
967                      super.isValidCharacter(aChar));
968         }
969     }
970
971
972     /**
973      * Represents a hex character, 0-9a-fA-F. a-f is mapped to A-F
974      */

975     private class HexCharacter extends MaskCharacter {
976         public boolean isValidCharacter(char aChar) {
977             return ((aChar == '0' || aChar == '1' ||
978                      aChar == '2' || aChar == '3' ||
979                      aChar == '4' || aChar == '5' ||
980                      aChar == '6' || aChar == '7' ||
981                      aChar == '8' || aChar == '9' ||
982                      aChar == 'a' || aChar == 'A' ||
983                      aChar == 'b' || aChar == 'B' ||
984                      aChar == 'c' || aChar == 'C' ||
985                      aChar == 'd' || aChar == 'D' ||
986                      aChar == 'e' || aChar == 'E' ||
987                      aChar == 'f' || aChar == 'F') &&
988                     super.isValidCharacter(aChar));
989         }
990
991         public char getChar(char aChar) {
992             if (Character.isDigit(aChar)) {
993                 return aChar;
994             }
995             return Character.toUpperCase(aChar);
996         }
997     }
998 }
999
Popular Tags