- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy pathInternationalFormatter.java
1061 lines (965 loc) · 36.4 KB
/
InternationalFormatter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2023, 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.
*/
packagejavax.swing.text;
importjava.awt.event.ActionEvent;
importjava.io.*;
importjava.text.*;
importjava.text.AttributedCharacterIterator.Attribute;
importjava.util.*;
importjavax.swing.*;
/**
* <code>InternationalFormatter</code> extends <code>DefaultFormatter</code>,
* using an instance of <code>java.text.Format</code> to handle the
* conversion to a String, and the conversion from a String.
* <p>
* If <code>getAllowsInvalid()</code> is false, this will ask the
* <code>Format</code> to format the current text on every edit.
* <p>
* You can specify a minimum and maximum value by way of the
* <code>setMinimum</code> and <code>setMaximum</code> methods. In order
* for this to work the values returned from <code>stringToValue</code> must be
* comparable to the min/max values by way of the <code>Comparable</code>
* interface.
* <p>
* Be careful how you configure the <code>Format</code> and the
* <code>InternationalFormatter</code>, as it is possible to create a
* situation where certain values can not be input. Consider the date
* format 'M/d/yy', an <code>InternationalFormatter</code> that is always
* valid (<code>setAllowsInvalid(false)</code>), is in overwrite mode
* (<code>setOverwriteMode(true)</code>) and the date 7/1/99. In this
* case the user will not be able to enter a two digit month or day of
* month. To avoid this, the format should be 'MM/dd/yy'.
* <p>
* If <code>InternationalFormatter</code> is configured to only allow valid
* values (<code>setAllowsInvalid(false)</code>), every valid edit will result
* in the text of the <code>JFormattedTextField</code> being completely reset
* from the <code>Format</code>.
* The cursor position will also be adjusted as literal characters are
* added/removed from the resulting String.
* <p>
* <code>InternationalFormatter</code>'s behavior of
* <code>stringToValue</code> is slightly different than that of
* <code>DefaultTextFormatter</code>, it does the following:
* <ol>
* <li><code>parseObject</code> is invoked on the <code>Format</code>
* specified by <code>setFormat</code>
* <li>If a Class has been set for the values (<code>setValueClass</code>),
* supers implementation is invoked to convert the value returned
* from <code>parseObject</code> to the appropriate class.
* <li>If a <code>ParseException</code> has not been thrown, and the value
* is outside the min/max a <code>ParseException</code> is thrown.
* <li>The value is returned.
* </ol>
* <code>InternationalFormatter</code> implements <code>stringToValue</code>
* in this manner so that you can specify an alternate Class than
* <code>Format</code> may return.
* <p>
* <strong>Warning:</strong>
* 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</code> package.
* Please see {@link java.beans.XMLEncoder}.
*
* @see java.text.Format
* @see java.lang.Comparable
*
* @since 1.4
*/
@SuppressWarnings("serial") // Same-version serialization only
publicclassInternationalFormatterextendsDefaultFormatter {
/**
* Used by <code>getFields</code>.
*/
privatestaticfinalFormat.Field[] EMPTY_FIELD_ARRAY =newFormat.Field[0];
/**
* Object used to handle the conversion.
*/
privateFormatformat;
/**
* Can be used to impose a maximum value.
*/
privateComparable<?> max;
/**
* Can be used to impose a minimum value.
*/
privateComparable<?> min;
/**
* <code>InternationalFormatter</code>'s behavior is dictated by a
* <code>AttributedCharacterIterator</code> that is obtained from
* the <code>Format</code>. On every edit, assuming
* allows invalid is false, the <code>Format</code> instance is invoked
* with <code>formatToCharacterIterator</code>. A <code>BitSet</code> is
* also kept up to date with the non-literal characters, that is
* for every index in the <code>AttributedCharacterIterator</code> an
* entry in the bit set is updated based on the return value from
* <code>isLiteral(Map)</code>. <code>isLiteral(int)</code> then uses
* this cached information.
* <p>
* If allowsInvalid is false, every edit results in resetting the complete
* text of the JTextComponent.
* <p>
* InternationalFormatterFilter can also provide two actions suitable for
* incrementing and decrementing. To enable this a subclass must
* override <code>getSupportsIncrement</code> to return true, and
* override <code>adjustValue</code> to handle the changing of the
* value. If you want to support changing the value outside of
* the valid FieldPositions, you will need to override
* <code>canIncrement</code>.
*/
/**
* A bit is set for every index identified in the
* AttributedCharacterIterator that is not considered decoration.
* This should only be used if validMask is true.
*/
privatetransientBitSetliteralMask;
/**
* Used to iterate over characters.
*/
privatetransientAttributedCharacterIteratoriterator;
/**
* True if the Format was able to convert the value to a String and
* back.
*/
privatetransientbooleanvalidMask;
/**
* Current value being displayed.
*/
privatetransientStringstring;
/**
* If true, DocumentFilter methods are unconditionally allowed,
* and no checking is done on their values. This is used when
* incrementing/decrementing via the actions.
*/
privatetransientbooleanignoreDocumentMutate;
/**
* Creates an <code>InternationalFormatter</code> with no
* <code>Format</code> specified.
*/
publicInternationalFormatter() {
setOverwriteMode(false);
}
/**
* Creates an <code>InternationalFormatter</code> with the specified
* <code>Format</code> instance.
*
* @param format Format instance used for converting from/to Strings
*/
publicInternationalFormatter(Formatformat) {
this();
setFormat(format);
}
/**
* Sets the format that dictates the legal values that can be edited
* and displayed.
*
* @param format <code>Format</code> instance used for converting
* from/to Strings
*/
publicvoidsetFormat(Formatformat) {
this.format = format;
}
/**
* Returns the format that dictates the legal values that can be edited
* and displayed.
*
* @return Format instance used for converting from/to Strings
*/
publicFormatgetFormat() {
returnformat;
}
/**
* Sets the minimum permissible value. If the <code>valueClass</code> has
* not been specified, and <code>minimum</code> is non null, the
* <code>valueClass</code> will be set to that of the class of
* <code>minimum</code>.
*
* @param minimum Minimum legal value that can be input
* @see #setValueClass
*/
publicvoidsetMinimum(Comparable<?> minimum) {
if (getValueClass() == null && minimum != null) {
setValueClass(minimum.getClass());
}
min = minimum;
}
/**
* Returns the minimum permissible value.
*
* @return Minimum legal value that can be input
*/
publicComparable<?> getMinimum() {
returnmin;
}
/**
* Sets the maximum permissible value. If the <code>valueClass</code> has
* not been specified, and <code>max</code> is non null, the
* <code>valueClass</code> will be set to that of the class of
* <code>max</code>.
*
* @param max Maximum legal value that can be input
* @see #setValueClass
*/
publicvoidsetMaximum(Comparable<?> max) {
if (getValueClass() == null && max != null) {
setValueClass(max.getClass());
}
this.max = max;
}
/**
* Returns the maximum permissible value.
*
* @return Maximum legal value that can be input
*/
publicComparable<?> getMaximum() {
returnmax;
}
/**
* Installs the <code>DefaultFormatter</code> onto a particular
* <code>JFormattedTextField</code>.
* This will invoke <code>valueToString</code> to convert the
* current value from the <code>JFormattedTextField</code> to
* a String. This will then install the <code>Action</code>s from
* <code>getActions</code>, the <code>DocumentFilter</code>
* returned from <code>getDocumentFilter</code> and the
* <code>NavigationFilter</code> returned from
* <code>getNavigationFilter</code> onto the
* <code>JFormattedTextField</code>.
* <p>
* Subclasses will typically only need to override this if they
* wish to install additional listeners on the
* <code>JFormattedTextField</code>.
* <p>
* If there is a <code>ParseException</code> in converting the
* current value to a String, this will set the text to an empty
* String, and mark the <code>JFormattedTextField</code> as being
* in an invalid state.
* <p>
* While this is a public method, this is typically only useful
* for subclassers of <code>JFormattedTextField</code>.
* <code>JFormattedTextField</code> 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.
*/
publicvoidinstall(JFormattedTextFieldftf) {
super.install(ftf);
updateMaskIfNecessary();
// invoked again as the mask should now be valid.
positionCursorAtInitialLocation();
}
/**
* Returns a String representation of the Object <code>value</code>.
* This invokes <code>format</code> on the current <code>Format</code>.
*
* @throws ParseException if there is an error in the conversion
* @param value Value to convert
* @return String representation of value
*/
publicStringvalueToString(Objectvalue) throwsParseException {
if (value == null) {
return"";
}
Formatf = getFormat();
if (f == null) {
returnvalue.toString();
}
returnf.format(value);
}
/**
* Returns the <code>Object</code> representation of the
* <code>String</code> <code>text</code>.
*
* @param text <code>String</code> to convert
* @return <code>Object</code> representation of text
* @throws ParseException if there is an error in the conversion
*/
publicObjectstringToValue(Stringtext) throwsParseException {
Objectvalue = stringToValue(text, getFormat());
// Convert to the value class if the Value returned from the
// Format does not match.
if (value != null && getValueClass() != null &&
!getValueClass().isInstance(value)) {
value = super.stringToValue(value.toString());
}
try {
if (!isValidValue(value, true)) {
thrownewParseException("Value not within min/max range", 0);
}
} catch (ClassCastExceptioncce) {
thrownewParseException("Class cast exception comparing values: "
+ cce, 0);
}
returnvalue;
}
/**
* Returns the <code>Format.Field</code> constants associated with
* the text at <code>offset</code>. If <code>offset</code> is not
* a valid location into the current text, this will return an
* empty array.
*
* @param offset offset into text to be examined
* @return Format.Field constants associated with the text at the
* given position.
*/
publicFormat.Field[] getFields(intoffset) {
if (getAllowsInvalid()) {
// This will work if the currently edited value is valid.
updateMask();
}
Map<Attribute, Object> attrs = getAttributes(offset);
if (attrs != null && attrs.size() > 0) {
ArrayList<Attribute> al = newArrayList<Attribute>();
al.addAll(attrs.keySet());
returnal.toArray(EMPTY_FIELD_ARRAY);
}
returnEMPTY_FIELD_ARRAY;
}
/**
* Creates a copy of the DefaultFormatter.
*
* @return copy of the DefaultFormatter
*/
publicObjectclone() throwsCloneNotSupportedException {
InternationalFormatterformatter = (InternationalFormatter)super.
clone();
formatter.literalMask = null;
formatter.iterator = null;
formatter.validMask = false;
formatter.string = null;
returnformatter;
}
/**
* If <code>getSupportsIncrement</code> returns true, this returns
* two Actions suitable for incrementing/decrementing the value.
*/
protectedAction[] getActions() {
if (getSupportsIncrement()) {
returnnewAction[] { newIncrementAction("increment", 1),
newIncrementAction("decrement", -1) };
}
returnnull;
}
/**
* Invokes <code>parseObject</code> on <code>f</code>, returning
* its value.
*/
ObjectstringToValue(Stringtext, Formatf) throwsParseException {
if (f == null) {
returntext;
}
returnf.parseObject(text);
}
/**
* Returns true if <code>value</code> is between the min/max.
*
* @param wantsCCE If false, and a ClassCastException is thrown in
* comparing the values, the exception is consumed and
* false is returned.
*/
booleanisValidValue(Objectvalue, booleanwantsCCE) {
@SuppressWarnings("unchecked")
Comparable<Object> min = (Comparable<Object>)getMinimum();
try {
if (min != null && min.compareTo(value) > 0) {
returnfalse;
}
} catch (ClassCastExceptioncce) {
if (wantsCCE) {
throwcce;
}
returnfalse;
}
@SuppressWarnings("unchecked")
Comparable<Object> max = (Comparable<Object>)getMaximum();
try {
if (max != null && max.compareTo(value) < 0) {
returnfalse;
}
} catch (ClassCastExceptioncce) {
if (wantsCCE) {
throwcce;
}
returnfalse;
}
returntrue;
}
/**
* Returns a Set of the attribute identifiers at <code>index</code>.
*/
Map<Attribute, Object> getAttributes(intindex) {
if (isValidMask()) {
AttributedCharacterIteratoriterator = getIterator();
if (index >= 0 && index <= iterator.getEndIndex()) {
iterator.setIndex(index);
returniterator.getAttributes();
}
}
returnnull;
}
/**
* Returns the start of the first run that contains the attribute
* <code>id</code>. This will return <code>-1</code> if the attribute
* can not be found.
*/
intgetAttributeStart(AttributedCharacterIterator.Attributeid) {
if (isValidMask()) {
AttributedCharacterIteratoriterator = getIterator();
iterator.first();
while (iterator.current() != CharacterIterator.DONE) {
if (iterator.getAttribute(id) != null) {
returniterator.getIndex();
}
iterator.next();
}
}
return -1;
}
/**
* Returns the <code>AttributedCharacterIterator</code> used to
* format the last value.
*/
AttributedCharacterIteratorgetIterator() {
returniterator;
}
/**
* Updates the AttributedCharacterIterator and bitset, if necessary.
*/
voidupdateMaskIfNecessary() {
if (!getAllowsInvalid() && (getFormat() != null)) {
if (!isValidMask()) {
updateMask();
}
else {
StringnewString = getFormattedTextField().getText();
if (!newString.equals(string)) {
updateMask();
}
}
}
}
/**
* Updates the AttributedCharacterIterator by invoking
* <code>formatToCharacterIterator</code> on the <code>Format</code>.
* If this is successful,
* <code>updateMask(AttributedCharacterIterator)</code>
* is then invoked to update the internal bitmask.
*/
voidupdateMask() {
if (getFormat() != null) {
Documentdoc = getFormattedTextField().getDocument();
validMask = false;
if (doc != null) {
try {
string = doc.getText(0, doc.getLength());
} catch (BadLocationExceptionble) {
string = null;
}
if (string != null) {
try {
Objectvalue = stringToValue(string);
AttributedCharacterIteratoriterator = getFormat().
formatToCharacterIterator(value);
updateMask(iterator);
}
catch (ParseException | NullPointerException | IllegalArgumentExceptione) {
}
}
}
}
}
/**
* Returns the number of literal characters before <code>index</code>.
*/
intgetLiteralCountTo(intindex) {
intlCount = 0;
for (intcounter = 0; counter < index; counter++) {
if (isLiteral(counter)) {
lCount++;
}
}
returnlCount;
}
/**
* Returns true if the character at index is a literal, that is
* not editable.
*/
booleanisLiteral(intindex) {
if (isValidMask() && index < string.length()) {
returnliteralMask.get(index);
}
returnfalse;
}
/**
* Returns the literal character at index.
*/
chargetLiteral(intindex) {
if (isValidMask() && string != null && index < string.length()) {
returnstring.charAt(index);
}
return (char)0;
}
/**
* Returns true if the character at offset is navigable too. This
* is implemented in terms of <code>isLiteral</code>, subclasses
* may wish to provide different behavior.
*/
booleanisNavigatable(intoffset) {
return !isLiteral(offset);
}
/**
* Overridden to update the mask after invoking supers implementation.
*/
voidupdateValue(Objectvalue) {
super.updateValue(value);
updateMaskIfNecessary();
}
/**
* Overridden to unconditionally allow the replace if
* ignoreDocumentMutate is true.
*/
voidreplace(DocumentFilter.FilterBypassfb, intoffset,
intlength, Stringtext,
AttributeSetattrs) throwsBadLocationException {
if (ignoreDocumentMutate) {
fb.replace(offset, length, text, attrs);
return;
}
super.replace(fb, offset, length, text, attrs);
}
/**
* Returns the index of the next non-literal character starting at
* index. If index is not a literal, it will be returned.
*
* @param direction Amount to increment looking for non-literal
*/
privateintgetNextNonliteralIndex(intindex, intdirection) {
intmax = getFormattedTextField().getDocument().getLength();
while (index >= 0 && index < max) {
if (isLiteral(index)) {
index += direction;
}
else {
returnindex;
}
}
return (direction == -1) ? 0 : max;
}
/**
* Overridden in an attempt to honor the literals.
* <p>If we do not allow invalid values and are in overwrite mode, this
* {@code rh.length} is corrected as to preserve trailing literals.
* If not in overwrite mode, and there is text to insert it is
* inserted at the next non literal index going forward. If there
* is only text to remove, it is removed from the next non literal
* index going backward.
*/
booleancanReplace(ReplaceHolderrh) {
if (!getAllowsInvalid()) {
Stringtext = rh.text;
inttl = (text != null) ? text.length() : 0;
JTextComponentc = getFormattedTextField();
if (tl == 0 && rh.length == 1 && c.getSelectionStart() != rh.offset) {
// Backspace, adjust to actually delete next non-literal.
rh.offset = getNextNonliteralIndex(rh.offset, -1);
} elseif (getOverwriteMode()) {
intpos = rh.offset;
inttextPos = pos;
booleanoverflown = false;
for (inti = 0; i < rh.length; i++) {
while (isLiteral(pos)) pos++;
if (pos >= string.length()) {
pos = textPos;
overflown = true;
break;
}
textPos = ++pos;
}
if (overflown || c.getSelectedText() == null) {
rh.length = pos - rh.offset;
}
}
elseif (tl > 0) {
// insert (or insert and remove)
rh.offset = getNextNonliteralIndex(rh.offset, 1);
}
else {
// remove only
rh.offset = getNextNonliteralIndex(rh.offset, -1);
}
((ExtendedReplaceHolder)rh).endOffset = rh.offset;
((ExtendedReplaceHolder)rh).endTextLength = (rh.text != null) ?
rh.text.length() : 0;
}
else {
((ExtendedReplaceHolder)rh).endOffset = rh.offset;
((ExtendedReplaceHolder)rh).endTextLength = (rh.text != null) ?
rh.text.length() : 0;
}
booleancan = super.canReplace(rh);
if (can && !getAllowsInvalid()) {
((ExtendedReplaceHolder)rh).resetFromValue(this);
}
returncan;
}
/**
* When in !allowsInvalid mode the text is reset on every edit, thus
* supers implementation will position the cursor at the wrong position.
* As such, this invokes supers implementation and then invokes
* <code>repositionCursor</code> to correctly reset the cursor.
*/
booleanreplace(ReplaceHolderrh) throwsBadLocationException {
intstart = -1;
intdirection = 1;
intliteralCount = -1;
if (rh.length > 0 && (rh.text == null || rh.text.length() == 0) &&
(getFormattedTextField().getSelectionStart() != rh.offset ||
rh.length > 1)) {
direction = -1;
}
if (!getAllowsInvalid()) {
if ((rh.text == null || rh.text.length() == 0) && rh.length > 0) {
// remove
start = getFormattedTextField().getSelectionStart();
}
else {
start = rh.offset;
}
literalCount = getLiteralCountTo(start);
}
if (super.replace(rh)) {
if (start != -1) {
intend = ((ExtendedReplaceHolder)rh).endOffset;
end += ((ExtendedReplaceHolder)rh).endTextLength;
repositionCursor(literalCount, end, direction);
}
else {
start = ((ExtendedReplaceHolder)rh).endOffset;
if (direction == 1) {
start += ((ExtendedReplaceHolder)rh).endTextLength;
}
repositionCursor(start, direction);
}
returntrue;
}
returnfalse;
}
/**
* Repositions the cursor. <code>startLiteralCount</code> gives
* the number of literals to the start of the deleted range, end
* gives the ending location to adjust from, direction gives
* the direction relative to <code>end</code> to position the
* cursor from.
*/
privatevoidrepositionCursor(intstartLiteralCount, intend,
intdirection) {
intendLiteralCount = getLiteralCountTo(end);
if (endLiteralCount != end) {
end -= startLiteralCount;
for (intcounter = 0; counter < end; counter++) {
if (isLiteral(counter)) {
end++;
}
}
}
repositionCursor(end, 1/*direction*/);
}
/**
* Returns the character from the mask that has been buffered
* at <code>index</code>.
*/
chargetBufferedChar(intindex) {
if (isValidMask()) {
if (string != null && index < string.length()) {
returnstring.charAt(index);
}
}
return (char)0;
}
/**
* Returns true if the current mask is valid.
*/
booleanisValidMask() {
returnvalidMask;
}
/**
* Returns true if <code>attributes</code> is null or empty.
*/
booleanisLiteral(Map<?, ?> attributes) {
return ((attributes == null) || attributes.size() == 0);
}
/**
* Updates the internal bitset from <code>iterator</code>. This will
* set <code>validMask</code> to true if <code>iterator</code> is
* non-null.
*/
privatevoidupdateMask(AttributedCharacterIteratoriterator) {
if (iterator != null) {
validMask = true;
this.iterator = iterator;
// Update the literal mask
if (literalMask == null) {
literalMask = newBitSet();
}
else {
for (intcounter = literalMask.length() - 1; counter >= 0;
counter--) {
literalMask.clear(counter);
}
}
iterator.first();
while (iterator.current() != CharacterIterator.DONE) {
Map<Attribute,Object> attributes = iterator.getAttributes();
booleanset = isLiteral(attributes);
intstart = iterator.getIndex();
intend = iterator.getRunLimit();
while (start < end) {
if (set) {
literalMask.set(start);
}
else {
literalMask.clear(start);
}
start++;
}
iterator.setIndex(start);
}
}
}
/**
* Returns true if <code>field</code> is non-null.
* Subclasses that wish to allow incrementing to happen outside of
* the known fields will need to override this.
*/
booleancanIncrement(Objectfield, intcursorPosition) {
return (field != null);
}
/**
* Selects the fields identified by <code>attributes</code>.
*/
voidselectField(Objectf, intcount) {
AttributedCharacterIteratoriterator = getIterator();
if (iterator != null &&
(finstanceofAttributedCharacterIterator.Attribute)) {
AttributedCharacterIterator.Attributefield =
(AttributedCharacterIterator.Attribute)f;
iterator.first();
while (iterator.current() != CharacterIterator.DONE) {
while (iterator.getAttribute(field) == null &&
iterator.next() != CharacterIterator.DONE);
if (iterator.current() != CharacterIterator.DONE) {
intlimit = iterator.getRunLimit(field);
if (--count <= 0) {
getFormattedTextField().select(iterator.getIndex(),
limit);
break;
}
iterator.setIndex(limit);
iterator.next();
}
}
}
}
/**
* Returns the field that will be adjusted by adjustValue.
*/
ObjectgetAdjustField(intstart, Map<?, ?> attributes) {
returnnull;
}
/**
* Returns the number of occurrences of <code>f</code> before
* the location <code>start</code> in the current
* <code>AttributedCharacterIterator</code>.
*/
privateintgetFieldTypeCountTo(Objectf, intstart) {
AttributedCharacterIteratoriterator = getIterator();
intcount = 0;
if (iterator != null &&
(finstanceofAttributedCharacterIterator.Attribute)) {
AttributedCharacterIterator.Attributefield =
(AttributedCharacterIterator.Attribute)f;
iterator.first();
while (iterator.getIndex() < start) {
while (iterator.getAttribute(field) == null &&
iterator.next() != CharacterIterator.DONE);
if (iterator.current() != CharacterIterator.DONE) {
iterator.setIndex(iterator.getRunLimit(field));
iterator.next();
count++;
}
else {
break;
}
}
}
returncount;
}
/**
* Subclasses supporting incrementing must override this to handle
* the actual incrementing. <code>value</code> is the current value,
* <code>attributes</code> gives the field the cursor is in (may be
* null depending upon <code>canIncrement</code>) and
* <code>direction</code> is the amount to increment by.
*/
ObjectadjustValue(Objectvalue, Map<?, ?> attributes, Objectfield,
intdirection) throws
BadLocationException, ParseException {
returnnull;
}
/**
* Returns false, indicating InternationalFormatter does not allow
* incrementing of the value. Subclasses that wish to support
* incrementing/decrementing the value should override this and
* return true. Subclasses should also override
* <code>adjustValue</code>.
*/
booleangetSupportsIncrement() {
returnfalse;
}
/**
* Resets the value of the JFormattedTextField to be
* <code>value</code>.
*/
voidresetValue(Objectvalue) throwsBadLocationException, ParseException {
Documentdoc = getFormattedTextField().getDocument();
Stringstring = valueToString(value);
try {
ignoreDocumentMutate = true;
doc.remove(0, doc.getLength());
doc.insertString(0, string, null);
} finally {
ignoreDocumentMutate = false;
}
updateValue(value);
}
/**
* Subclassed to update the internal representation of the mask after
* the default read operation has completed.
*/
@Serial
privatevoidreadObject(ObjectInputStreams)
throwsIOException, ClassNotFoundException {
s.defaultReadObject();
updateMaskIfNecessary();
}
/**
* Overridden to return an instance of <code>ExtendedReplaceHolder</code>.
*/
ReplaceHoldergetReplaceHolder(DocumentFilter.FilterBypassfb, intoffset,
intlength, Stringtext,
AttributeSetattrs) {
if (replaceHolder == null) {
replaceHolder = newExtendedReplaceHolder();
}
returnsuper.getReplaceHolder(fb, offset, length, text, attrs);
}
/**
* As InternationalFormatter replaces the complete text on every edit,
* ExtendedReplaceHolder keeps track of the offset and length passed
* into canReplace.
*/
staticclassExtendedReplaceHolderextendsReplaceHolder {
/** Offset of the insert/remove. This may differ from offset in
* that if !allowsInvalid the text is replaced on every edit. */
intendOffset;
/** Length of the text. This may differ from text.length in
* that if !allowsInvalid the text is replaced on every edit. */
intendTextLength;
/**
* Resets the region to delete to be the complete document and
* the text from invoking valueToString on the current value.
*/
voidresetFromValue(InternationalFormatterformatter) {
// Need to reset the complete string as Format's result can
// be completely different.
offset = 0;
try {
text = formatter.valueToString(value);
} catch (ParseExceptionpe) {
// Should never happen, otherwise canReplace would have
// returned value.
text = "";
}
length = fb.getDocument().getLength();
}
}
/**
* IncrementAction is used to increment the value by a certain amount.
* It calls into <code>adjustValue</code> to handle the actual
* incrementing of the value.