2
|
1 |
/*
|
|
2 |
* Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
|
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
|
4 |
*
|
|
5 |
* This code is free software; you can redistribute it and/or modify it
|
|
6 |
* under the terms of the GNU General Public License version 2 only, as
|
|
7 |
* published by the Free Software Foundation. Sun designates this
|
|
8 |
* particular file as subject to the "Classpath" exception as provided
|
|
9 |
* by Sun in the LICENSE file that accompanied this code.
|
|
10 |
*
|
|
11 |
* This code is distributed in the hope that it will be useful, but WITHOUT
|
|
12 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
13 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
|
14 |
* version 2 for more details (a copy is included in the LICENSE file that
|
|
15 |
* accompanied this code).
|
|
16 |
*
|
|
17 |
* You should have received a copy of the GNU General Public License version
|
|
18 |
* 2 along with this work; if not, write to the Free Software Foundation,
|
|
19 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
|
20 |
*
|
|
21 |
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
|
|
22 |
* CA 95054 USA or visit www.sun.com if you need additional information or
|
|
23 |
* have any questions.
|
|
24 |
*/
|
|
25 |
package javax.swing.text;
|
|
26 |
|
|
27 |
import java.lang.reflect.*;
|
|
28 |
import java.text.*;
|
|
29 |
import java.util.*;
|
|
30 |
import javax.swing.text.*;
|
|
31 |
|
|
32 |
/**
|
|
33 |
* <code>NumberFormatter</code> subclasses <code>InternationalFormatter</code>
|
|
34 |
* adding special behavior for numbers. Among the specializations are
|
|
35 |
* (these are only used if the <code>NumberFormatter</code> does not display
|
|
36 |
* invalid nubers, eg <code>setAllowsInvalid(false)</code>):
|
|
37 |
* <ul>
|
|
38 |
* <li>Pressing +/- (- is determined from the
|
|
39 |
* <code>DecimalFormatSymbols</code> associated with the
|
|
40 |
* <code>DecimalFormat</code>) in any field but the exponent
|
|
41 |
* field will attempt to change the sign of the number to
|
|
42 |
* positive/negative.
|
|
43 |
* <li>Pressing +/- (- is determined from the
|
|
44 |
* <code>DecimalFormatSymbols</code> associated with the
|
|
45 |
* <code>DecimalFormat</code>) in the exponent field will
|
|
46 |
* attemp to change the sign of the exponent to positive/negative.
|
|
47 |
* </ul>
|
|
48 |
* <p>
|
|
49 |
* If you are displaying scientific numbers, you may wish to turn on
|
|
50 |
* overwrite mode, <code>setOverwriteMode(true)</code>. For example:
|
|
51 |
* <pre>
|
|
52 |
* DecimalFormat decimalFormat = new DecimalFormat("0.000E0");
|
|
53 |
* NumberFormatter textFormatter = new NumberFormatter(decimalFormat);
|
|
54 |
* textFormatter.setOverwriteMode(true);
|
|
55 |
* textFormatter.setAllowsInvalid(false);
|
|
56 |
* </pre>
|
|
57 |
* <p>
|
|
58 |
* If you are going to allow the user to enter decimal
|
|
59 |
* values, you should either force the DecimalFormat to contain at least
|
|
60 |
* one decimal (<code>#.0###</code>), or allow the value to be invalid
|
|
61 |
* <code>setAllowsInvalid(true)</code>. Otherwise users may not be able to
|
|
62 |
* input decimal values.
|
|
63 |
* <p>
|
|
64 |
* <code>NumberFormatter</code> provides slightly different behavior to
|
|
65 |
* <code>stringToValue</code> than that of its superclass. If you have
|
|
66 |
* specified a Class for values, {@link #setValueClass}, that is one of
|
|
67 |
* of <code>Integer</code>, <code>Long</code>, <code>Float</code>,
|
|
68 |
* <code>Double</code>, <code>Byte</code> or <code>Short</code> and
|
|
69 |
* the Format's <code>parseObject</code> returns an instance of
|
|
70 |
* <code>Number</code>, the corresponding instance of the value class
|
|
71 |
* will be created using the constructor appropriate for the primitive
|
|
72 |
* type the value class represents. For example:
|
|
73 |
* <code>setValueClass(Integer.class)</code> will cause the resulting
|
|
74 |
* value to be created via
|
|
75 |
* <code>new Integer(((Number)formatter.parseObject(string)).intValue())</code>.
|
|
76 |
* This is typically useful if you
|
|
77 |
* wish to set a min/max value as the various <code>Number</code>
|
|
78 |
* implementations are generally not comparable to each other. This is also
|
|
79 |
* useful if for some reason you need a specific <code>Number</code>
|
|
80 |
* implementation for your values.
|
|
81 |
* <p>
|
|
82 |
* <strong>Warning:</strong>
|
|
83 |
* Serialized objects of this class will not be compatible with
|
|
84 |
* future Swing releases. The current serialization support is
|
|
85 |
* appropriate for short term storage or RMI between applications running
|
|
86 |
* the same version of Swing. As of 1.4, support for long term storage
|
|
87 |
* of all JavaBeans<sup><font size="-2">TM</font></sup>
|
|
88 |
* has been added to the <code>java.beans</code> package.
|
|
89 |
* Please see {@link java.beans.XMLEncoder}.
|
|
90 |
*
|
|
91 |
* @since 1.4
|
|
92 |
*/
|
|
93 |
public class NumberFormatter extends InternationalFormatter {
|
|
94 |
/** The special characters from the Format instance. */
|
|
95 |
private String specialChars;
|
|
96 |
|
|
97 |
/**
|
|
98 |
* Creates a <code>NumberFormatter</code> with the a default
|
|
99 |
* <code>NumberFormat</code> instance obtained from
|
|
100 |
* <code>NumberFormat.getNumberInstance()</code>.
|
|
101 |
*/
|
|
102 |
public NumberFormatter() {
|
|
103 |
this(NumberFormat.getNumberInstance());
|
|
104 |
}
|
|
105 |
|
|
106 |
/**
|
|
107 |
* Creates a NumberFormatter with the specified Format instance.
|
|
108 |
*
|
|
109 |
* @param format Format used to dictate legal values
|
|
110 |
*/
|
|
111 |
public NumberFormatter(NumberFormat format) {
|
|
112 |
super(format);
|
|
113 |
setFormat(format);
|
|
114 |
setAllowsInvalid(true);
|
|
115 |
setCommitsOnValidEdit(false);
|
|
116 |
setOverwriteMode(false);
|
|
117 |
}
|
|
118 |
|
|
119 |
/**
|
|
120 |
* Sets the format that dictates the legal values that can be edited
|
|
121 |
* and displayed.
|
|
122 |
* <p>
|
|
123 |
* If you have used the nullary constructor the value of this property
|
|
124 |
* will be determined for the current locale by way of the
|
|
125 |
* <code>NumberFormat.getNumberInstance()</code> method.
|
|
126 |
*
|
|
127 |
* @param format NumberFormat instance used to dictate legal values
|
|
128 |
*/
|
|
129 |
public void setFormat(Format format) {
|
|
130 |
super.setFormat(format);
|
|
131 |
|
|
132 |
DecimalFormatSymbols dfs = getDecimalFormatSymbols();
|
|
133 |
|
|
134 |
if (dfs != null) {
|
|
135 |
StringBuffer sb = new StringBuffer();
|
|
136 |
|
|
137 |
sb.append(dfs.getCurrencySymbol());
|
|
138 |
sb.append(dfs.getDecimalSeparator());
|
|
139 |
sb.append(dfs.getGroupingSeparator());
|
|
140 |
sb.append(dfs.getInfinity());
|
|
141 |
sb.append(dfs.getInternationalCurrencySymbol());
|
|
142 |
sb.append(dfs.getMinusSign());
|
|
143 |
sb.append(dfs.getMonetaryDecimalSeparator());
|
|
144 |
sb.append(dfs.getNaN());
|
|
145 |
sb.append(dfs.getPercent());
|
|
146 |
sb.append('+');
|
|
147 |
specialChars = sb.toString();
|
|
148 |
}
|
|
149 |
else {
|
|
150 |
specialChars = "";
|
|
151 |
}
|
|
152 |
}
|
|
153 |
|
|
154 |
/**
|
|
155 |
* Invokes <code>parseObject</code> on <code>f</code>, returning
|
|
156 |
* its value.
|
|
157 |
*/
|
|
158 |
Object stringToValue(String text, Format f) throws ParseException {
|
|
159 |
if (f == null) {
|
|
160 |
return text;
|
|
161 |
}
|
|
162 |
Object value = f.parseObject(text);
|
|
163 |
|
|
164 |
return convertValueToValueClass(value, getValueClass());
|
|
165 |
}
|
|
166 |
|
|
167 |
/**
|
|
168 |
* Converts the passed in value to the passed in class. This only
|
|
169 |
* works if <code>valueClass</code> is one of <code>Integer</code>,
|
|
170 |
* <code>Long</code>, <code>Float</code>, <code>Double</code>,
|
|
171 |
* <code>Byte</code> or <code>Short</code> and <code>value</code>
|
|
172 |
* is an instanceof <code>Number</code>.
|
|
173 |
*/
|
|
174 |
private Object convertValueToValueClass(Object value, Class valueClass) {
|
|
175 |
if (valueClass != null && (value instanceof Number)) {
|
|
176 |
if (valueClass == Integer.class) {
|
|
177 |
return new Integer(((Number)value).intValue());
|
|
178 |
}
|
|
179 |
else if (valueClass == Long.class) {
|
|
180 |
return new Long(((Number)value).longValue());
|
|
181 |
}
|
|
182 |
else if (valueClass == Float.class) {
|
|
183 |
return new Float(((Number)value).floatValue());
|
|
184 |
}
|
|
185 |
else if (valueClass == Double.class) {
|
|
186 |
return new Double(((Number)value).doubleValue());
|
|
187 |
}
|
|
188 |
else if (valueClass == Byte.class) {
|
|
189 |
return new Byte(((Number)value).byteValue());
|
|
190 |
}
|
|
191 |
else if (valueClass == Short.class) {
|
|
192 |
return new Short(((Number)value).shortValue());
|
|
193 |
}
|
|
194 |
}
|
|
195 |
return value;
|
|
196 |
}
|
|
197 |
|
|
198 |
/**
|
|
199 |
* Returns the character that is used to toggle to positive values.
|
|
200 |
*/
|
|
201 |
private char getPositiveSign() {
|
|
202 |
return '+';
|
|
203 |
}
|
|
204 |
|
|
205 |
/**
|
|
206 |
* Returns the character that is used to toggle to negative values.
|
|
207 |
*/
|
|
208 |
private char getMinusSign() {
|
|
209 |
DecimalFormatSymbols dfs = getDecimalFormatSymbols();
|
|
210 |
|
|
211 |
if (dfs != null) {
|
|
212 |
return dfs.getMinusSign();
|
|
213 |
}
|
|
214 |
return '-';
|
|
215 |
}
|
|
216 |
|
|
217 |
/**
|
|
218 |
* Returns the character that is used to toggle to negative values.
|
|
219 |
*/
|
|
220 |
private char getDecimalSeparator() {
|
|
221 |
DecimalFormatSymbols dfs = getDecimalFormatSymbols();
|
|
222 |
|
|
223 |
if (dfs != null) {
|
|
224 |
return dfs.getDecimalSeparator();
|
|
225 |
}
|
|
226 |
return '.';
|
|
227 |
}
|
|
228 |
|
|
229 |
/**
|
|
230 |
* Returns the DecimalFormatSymbols from the Format instance.
|
|
231 |
*/
|
|
232 |
private DecimalFormatSymbols getDecimalFormatSymbols() {
|
|
233 |
Format f = getFormat();
|
|
234 |
|
|
235 |
if (f instanceof DecimalFormat) {
|
|
236 |
return ((DecimalFormat)f).getDecimalFormatSymbols();
|
|
237 |
}
|
|
238 |
return null;
|
|
239 |
}
|
|
240 |
|
|
241 |
/**
|
|
242 |
*/
|
|
243 |
private boolean isValidInsertionCharacter(char aChar) {
|
|
244 |
return (Character.isDigit(aChar) || specialChars.indexOf(aChar) != -1);
|
|
245 |
}
|
|
246 |
|
|
247 |
|
|
248 |
/**
|
|
249 |
* Subclassed to return false if <code>text</code> contains in an invalid
|
|
250 |
* character to insert, that is, it is not a digit
|
|
251 |
* (<code>Character.isDigit()</code>) and
|
|
252 |
* not one of the characters defined by the DecimalFormatSymbols.
|
|
253 |
*/
|
|
254 |
boolean isLegalInsertText(String text) {
|
|
255 |
if (getAllowsInvalid()) {
|
|
256 |
return true;
|
|
257 |
}
|
|
258 |
for (int counter = text.length() - 1; counter >= 0; counter--) {
|
|
259 |
char aChar = text.charAt(counter);
|
|
260 |
|
|
261 |
if (!Character.isDigit(aChar) &&
|
|
262 |
specialChars.indexOf(aChar) == -1){
|
|
263 |
return false;
|
|
264 |
}
|
|
265 |
}
|
|
266 |
return true;
|
|
267 |
}
|
|
268 |
|
|
269 |
/**
|
|
270 |
* Subclassed to treat the decimal separator, grouping separator,
|
|
271 |
* exponent symbol, percent, permille, currency and sign as literals.
|
|
272 |
*/
|
|
273 |
boolean isLiteral(Map attrs) {
|
|
274 |
if (!super.isLiteral(attrs)) {
|
|
275 |
if (attrs == null) {
|
|
276 |
return false;
|
|
277 |
}
|
|
278 |
int size = attrs.size();
|
|
279 |
|
|
280 |
if (attrs.get(NumberFormat.Field.GROUPING_SEPARATOR) != null) {
|
|
281 |
size--;
|
|
282 |
if (attrs.get(NumberFormat.Field.INTEGER) != null) {
|
|
283 |
size--;
|
|
284 |
}
|
|
285 |
}
|
|
286 |
if (attrs.get(NumberFormat.Field.EXPONENT_SYMBOL) != null) {
|
|
287 |
size--;
|
|
288 |
}
|
|
289 |
if (attrs.get(NumberFormat.Field.PERCENT) != null) {
|
|
290 |
size--;
|
|
291 |
}
|
|
292 |
if (attrs.get(NumberFormat.Field.PERMILLE) != null) {
|
|
293 |
size--;
|
|
294 |
}
|
|
295 |
if (attrs.get(NumberFormat.Field.CURRENCY) != null) {
|
|
296 |
size--;
|
|
297 |
}
|
|
298 |
if (attrs.get(NumberFormat.Field.SIGN) != null) {
|
|
299 |
size--;
|
|
300 |
}
|
|
301 |
if (size == 0) {
|
|
302 |
return true;
|
|
303 |
}
|
|
304 |
return false;
|
|
305 |
}
|
|
306 |
return true;
|
|
307 |
}
|
|
308 |
|
|
309 |
/**
|
|
310 |
* Subclassed to make the decimal separator navigatable, as well
|
|
311 |
* as making the character between the integer field and the next
|
|
312 |
* field navigatable.
|
|
313 |
*/
|
|
314 |
boolean isNavigatable(int index) {
|
|
315 |
if (!super.isNavigatable(index)) {
|
|
316 |
// Don't skip the decimal, it causes wierd behavior
|
|
317 |
if (getBufferedChar(index) == getDecimalSeparator()) {
|
|
318 |
return true;
|
|
319 |
}
|
|
320 |
return false;
|
|
321 |
}
|
|
322 |
return true;
|
|
323 |
}
|
|
324 |
|
|
325 |
/**
|
|
326 |
* Returns the first <code>NumberFormat.Field</code> starting
|
|
327 |
* <code>index</code> incrementing by <code>direction</code>.
|
|
328 |
*/
|
|
329 |
private NumberFormat.Field getFieldFrom(int index, int direction) {
|
|
330 |
if (isValidMask()) {
|
|
331 |
int max = getFormattedTextField().getDocument().getLength();
|
|
332 |
AttributedCharacterIterator iterator = getIterator();
|
|
333 |
|
|
334 |
if (index >= max) {
|
|
335 |
index += direction;
|
|
336 |
}
|
|
337 |
while (index >= 0 && index < max) {
|
|
338 |
iterator.setIndex(index);
|
|
339 |
|
|
340 |
Map attrs = iterator.getAttributes();
|
|
341 |
|
|
342 |
if (attrs != null && attrs.size() > 0) {
|
|
343 |
Iterator keys = attrs.keySet().iterator();
|
|
344 |
|
|
345 |
while (keys.hasNext()) {
|
|
346 |
Object key = keys.next();
|
|
347 |
|
|
348 |
if (key instanceof NumberFormat.Field) {
|
|
349 |
return (NumberFormat.Field)key;
|
|
350 |
}
|
|
351 |
}
|
|
352 |
}
|
|
353 |
index += direction;
|
|
354 |
}
|
|
355 |
}
|
|
356 |
return null;
|
|
357 |
}
|
|
358 |
|
|
359 |
/**
|
|
360 |
* Overriden to toggle the value if the positive/minus sign
|
|
361 |
* is inserted.
|
|
362 |
*/
|
|
363 |
void replace(DocumentFilter.FilterBypass fb, int offset, int length,
|
|
364 |
String string, AttributeSet attr) throws BadLocationException {
|
|
365 |
if (!getAllowsInvalid() && length == 0 && string != null &&
|
|
366 |
string.length() == 1 &&
|
|
367 |
toggleSignIfNecessary(fb, offset, string.charAt(0))) {
|
|
368 |
return;
|
|
369 |
}
|
|
370 |
super.replace(fb, offset, length, string, attr);
|
|
371 |
}
|
|
372 |
|
|
373 |
/**
|
|
374 |
* Will change the sign of the integer or exponent field if
|
|
375 |
* <code>aChar</code> is the positive or minus sign. Returns
|
|
376 |
* true if a sign change was attempted.
|
|
377 |
*/
|
|
378 |
private boolean toggleSignIfNecessary(DocumentFilter.FilterBypass fb,
|
|
379 |
int offset, char aChar) throws
|
|
380 |
BadLocationException {
|
|
381 |
if (aChar == getMinusSign() || aChar == getPositiveSign()) {
|
|
382 |
NumberFormat.Field field = getFieldFrom(offset, -1);
|
|
383 |
Object newValue;
|
|
384 |
|
|
385 |
try {
|
|
386 |
if (field == null ||
|
|
387 |
(field != NumberFormat.Field.EXPONENT &&
|
|
388 |
field != NumberFormat.Field.EXPONENT_SYMBOL &&
|
|
389 |
field != NumberFormat.Field.EXPONENT_SIGN)) {
|
|
390 |
newValue = toggleSign((aChar == getPositiveSign()));
|
|
391 |
}
|
|
392 |
else {
|
|
393 |
// exponent
|
|
394 |
newValue = toggleExponentSign(offset, aChar);
|
|
395 |
}
|
|
396 |
if (newValue != null && isValidValue(newValue, false)) {
|
|
397 |
int lc = getLiteralCountTo(offset);
|
|
398 |
String string = valueToString(newValue);
|
|
399 |
|
|
400 |
fb.remove(0, fb.getDocument().getLength());
|
|
401 |
fb.insertString(0, string, null);
|
|
402 |
updateValue(newValue);
|
|
403 |
repositionCursor(getLiteralCountTo(offset) -
|
|
404 |
lc + offset, 1);
|
|
405 |
return true;
|
|
406 |
}
|
|
407 |
} catch (ParseException pe) {
|
|
408 |
invalidEdit();
|
|
409 |
}
|
|
410 |
}
|
|
411 |
return false;
|
|
412 |
}
|
|
413 |
|
|
414 |
/**
|
|
415 |
* Returns true if the range offset to length identifies the only
|
|
416 |
* integer field.
|
|
417 |
*/
|
|
418 |
private boolean isOnlyIntegerField(int offset, int length) {
|
|
419 |
if (isValidMask()) {
|
|
420 |
int start = getAttributeStart(NumberFormat.Field.INTEGER);
|
|
421 |
|
|
422 |
if (start != -1) {
|
|
423 |
AttributedCharacterIterator iterator = getIterator();
|
|
424 |
|
|
425 |
iterator.setIndex(start);
|
|
426 |
if (offset > start || iterator.getRunLimit(
|
|
427 |
NumberFormat.Field.INTEGER) > (offset + length)) {
|
|
428 |
return false;
|
|
429 |
}
|
|
430 |
return true;
|
|
431 |
}
|
|
432 |
}
|
|
433 |
return false;
|
|
434 |
}
|
|
435 |
|
|
436 |
/**
|
|
437 |
* Invoked to toggle the sign. For this to work the value class
|
|
438 |
* must have a single arg constructor that takes a String.
|
|
439 |
*/
|
|
440 |
private Object toggleSign(boolean positive) throws ParseException {
|
|
441 |
Object value = stringToValue(getFormattedTextField().getText());
|
|
442 |
|
|
443 |
if (value != null) {
|
|
444 |
// toString isn't localized, so that using +/- should work
|
|
445 |
// correctly.
|
|
446 |
String string = value.toString();
|
|
447 |
|
|
448 |
if (string != null && string.length() > 0) {
|
|
449 |
if (positive) {
|
|
450 |
if (string.charAt(0) == '-') {
|
|
451 |
string = string.substring(1);
|
|
452 |
}
|
|
453 |
}
|
|
454 |
else {
|
|
455 |
if (string.charAt(0) == '+') {
|
|
456 |
string = string.substring(1);
|
|
457 |
}
|
|
458 |
if (string.length() > 0 && string.charAt(0) != '-') {
|
|
459 |
string = "-" + string;
|
|
460 |
}
|
|
461 |
}
|
|
462 |
if (string != null) {
|
|
463 |
Class valueClass = getValueClass();
|
|
464 |
|
|
465 |
if (valueClass == null) {
|
|
466 |
valueClass = value.getClass();
|
|
467 |
}
|
|
468 |
try {
|
|
469 |
Constructor cons = valueClass.getConstructor(
|
|
470 |
new Class[] { String.class });
|
|
471 |
|
|
472 |
if (cons != null) {
|
|
473 |
return cons.newInstance(new Object[]{string});
|
|
474 |
}
|
|
475 |
} catch (Throwable ex) { }
|
|
476 |
}
|
|
477 |
}
|
|
478 |
}
|
|
479 |
return null;
|
|
480 |
}
|
|
481 |
|
|
482 |
/**
|
|
483 |
* Invoked to toggle the sign of the exponent (for scientific
|
|
484 |
* numbers).
|
|
485 |
*/
|
|
486 |
private Object toggleExponentSign(int offset, char aChar) throws
|
|
487 |
BadLocationException, ParseException {
|
|
488 |
String string = getFormattedTextField().getText();
|
|
489 |
int replaceLength = 0;
|
|
490 |
int loc = getAttributeStart(NumberFormat.Field.EXPONENT_SIGN);
|
|
491 |
|
|
492 |
if (loc >= 0) {
|
|
493 |
replaceLength = 1;
|
|
494 |
offset = loc;
|
|
495 |
}
|
|
496 |
if (aChar == getPositiveSign()) {
|
|
497 |
string = getReplaceString(offset, replaceLength, null);
|
|
498 |
}
|
|
499 |
else {
|
|
500 |
string = getReplaceString(offset, replaceLength,
|
|
501 |
new String(new char[] { aChar }));
|
|
502 |
}
|
|
503 |
return stringToValue(string);
|
|
504 |
}
|
|
505 |
}
|