javax.swing.text
Class NumberFormatter

java.lang.Object
  |
  +--javax.swing.JFormattedTextField.AbstractFormatter
        |
        +--javax.swing.text.DefaultFormatter
              |
              +--javax.swing.text.InternationalFormatter
                    |
                    +--javax.swing.text.NumberFormatter
All Implemented Interfaces:
Cloneable, Serializable
Direct Known Subclasses:
javax.swing.JSpinner.NumberEditorFormatter

public class NumberFormatter
extends InternationalFormatter

Safe: NumberFormatter subclasses InternationalFormatter adding special behavior for numbers. Among the specializations are (these are only used if the NumberFormatter does not display invalid nubers, eg setAllowsInvalid(false)):

If you are displaying scientific numbers, you may wish to turn on overwrite mode, setOverwriteMode(true). For example:

 DecimalFormat decimalFormat = new DecimalFormat("0.000E0");
 NumberFormatter textFormatter = new NumberFormatter(decimalFormat);
 textFormatter.setOverwriteMode(true);
 textFormatter.setAllowsInvalid(false);
 

If you are going to allow the user to enter decimal values, you should either force the DecimalFormat to contain at least one decimal (#.0###), or allow the value to be invalid setAllowsInvalid(true). Otherwise users may not be able to input decimal values.

NumberFormatter provides slightly different behavior to stringToValue than that of its superclass. If you have specified a Class for values, DefaultFormatter.setValueClass(java.lang.Class), that is one of of Integer, Long, Float, Double, Byte or Short and the Format's parseObject returns an instance of Number, the corresponding instance of the value class will be created using the constructor appropriate for the primitive type the value class represents. For example: setValueClass(Integer.class) will cause the resulting value to be created via new Integer(((Number)formatter.parseObject(string)).intValue()). This is typically useful if you wish to set a min/max value as the various Number implementations are generally not comparable to each other. This is also useful if for some reason you need a specific Number implementation for your values.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see java.beans.XMLEncoder.

Since:
1.4
Version:
1.4 03/05/01
See Also:
Serialized Form

Field Summary
private  String specialChars
          The special characters from the Format instance.
 
Fields inherited from class javax.swing.text.InternationalFormatter
 
Fields inherited from class javax.swing.text.DefaultFormatter
replaceHolder
 
Fields inherited from class javax.swing.AbstractFormatter
 
Constructor Summary
NumberFormatter()
          Enabled: Creates a NumberFormatter with the a default NumberFormat instance obtained from NumberFormat.getNumberInstance().
NumberFormatter(java.text.NumberFormat format)
          Enabled: Creates a NumberFormatter with the specified Format instance.
 
Method Summary
private  Object convertValueToValueClass(Object value, Class valueClass)
          Converts the passed in value to the passed in class.
private  java.text.DecimalFormatSymbols getDecimalFormatSymbols()
          Returns the DecimalFormatSymbols from the Format instance.
private  char getDecimalSeparator()
          Returns the character that is used to toggle to negative values.
private  java.text.NumberFormat.Field getFieldFrom(int index, int direction)
          Returns the first NumberFormat.Field starting index incrementing by direction.
private  char getMinusSign()
          Returns the character that is used to toggle to negative values.
private  char getPositiveSign()
          Returns the character that is used to toggle to positive values.
(package private)  boolean isLegalInsertText(String text)
          Subclassed to return false if text contains in an invalid character to insert, that is, it is not a digit (Character.isDigit()) and not one of the characters defined by the DecimalFormatSymbols.
(package private)  boolean isLiteral(Map attrs)
          Subclassed to treat the decimal separator, grouping separator, exponent symbol, percent, permille and currency as literals.
(package private)  boolean isNavigatable(int index)
          Subclassed to make the decimal separator navigatable, as well as making the character between the integer field and the next field navigatable.
private  boolean isOnlyIntegerField(int offset, int length)
          Returns true if the range offset to length identifies the only integer field.
private  boolean isValidInsertionCharacter(char aChar)
           
(package private)  void replace(javax.swing.text.DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr)
          Overriden to toggle the value if the positive/minus sign is inserted.
 void setFormat(java.text.Format format)
          Enabled: Sets the format that dictates the legal values that can be edited and displayed.
(package private)  Object stringToValue(String text, java.text.Format f)
          Invokes parseObject on f, returning its value.
private  Object toggleExponentSign(int offset, char aChar)
          Invoked to toggle the sign of the exponent (for scientific numbers).
private  Object toggleSign(boolean positive)
          Invoked to toggle the sign.
private  boolean toggleSignIfNecessary(javax.swing.text.DocumentFilter.FilterBypass fb, int offset, char aChar)
          Will change the sign of the integer or exponent field if aChar is the positive or minus sign.
 
Methods inherited from class javax.swing.text.InternationalFormatter
adjustValue, canIncrement, canReplace, clone, getActions, getAdjustField, getAttributes, getAttributeStart, getBufferedChar, getFields, getFormat, getIterator, getLiteral, getLiteralCountTo, getMaximum, getMinimum, getReplaceHolder, getSupportsIncrement, install, isLiteral, isValidMask, isValidValue, replace, resetValue, selectField, setMaximum, setMinimum, stringToValue, updateMask, updateMaskIfNecessary, updateValue, valueToString
 
Methods inherited from class javax.swing.text.DefaultFormatter
commitEdit, getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getInitialVisualPosition, getNavigationFilter, getNextCursorPosition, getNextVisualPositionFrom, getOverwriteMode, getReplaceString, getValueClass, isValidEdit, moveDot, positionCursorAtInitialLocation, repositionCursor, setAllowsInvalid, setCommitsOnValidEdit, setDot, setOverwriteMode, setValueClass, updateValue
 
Methods inherited from class javax.swing.AbstractFormatter
getFormattedTextField, invalidEdit, setEditValid, uninstall
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

specialChars

private String specialChars
The special characters from the Format instance.

Constructor Detail

NumberFormatter

public NumberFormatter()
Enabled: Creates a NumberFormatter with the a default NumberFormat instance obtained from NumberFormat.getNumberInstance().


NumberFormatter

public NumberFormatter(java.text.NumberFormat format)
Enabled: Creates a NumberFormatter with the specified Format instance.

Parameters:
format - Format used to dictate legal values
Method Detail

setFormat

public void setFormat(java.text.Format format)
Enabled: Sets the format that dictates the legal values that can be edited and displayed.

If you have used the nullary constructor the value of this property will be determined for the current locale by way of the NumberFormat.getNumberInstance() method.

Overrides:
setFormat in class InternationalFormatter
Parameters:
format - NumberFormat instance used to dictate legal values

stringToValue

Object stringToValue(String text,
                     java.text.Format f)
               throws java.text.ParseException
Invokes parseObject on f, returning its value.

Overrides:
stringToValue in class InternationalFormatter
java.text.ParseException

convertValueToValueClass

private Object convertValueToValueClass(Object value,
                                        Class valueClass)
Converts the passed in value to the passed in class. This only works if valueClass is one of Integer, Long, Float, Double, Byte or Short and value is an instanceof Number.


getPositiveSign

private char getPositiveSign()
Returns the character that is used to toggle to positive values.


getMinusSign

private char getMinusSign()
Returns the character that is used to toggle to negative values.


getDecimalSeparator

private char getDecimalSeparator()
Returns the character that is used to toggle to negative values.


getDecimalFormatSymbols

private java.text.DecimalFormatSymbols getDecimalFormatSymbols()
Returns the DecimalFormatSymbols from the Format instance.


isValidInsertionCharacter

private boolean isValidInsertionCharacter(char aChar)

isLegalInsertText

boolean isLegalInsertText(String text)
Subclassed to return false if text contains in an invalid character to insert, that is, it is not a digit (Character.isDigit()) and not one of the characters defined by the DecimalFormatSymbols.

Overrides:
isLegalInsertText in class DefaultFormatter

isLiteral

boolean isLiteral(Map attrs)
Subclassed to treat the decimal separator, grouping separator, exponent symbol, percent, permille and currency as literals.

Overrides:
isLiteral in class InternationalFormatter

isNavigatable

boolean isNavigatable(int index)
Subclassed to make the decimal separator navigatable, as well as making the character between the integer field and the next field navigatable.

Overrides:
isNavigatable in class InternationalFormatter

getFieldFrom

private java.text.NumberFormat.Field getFieldFrom(int index,
                                                  int direction)
Returns the first NumberFormat.Field starting index incrementing by direction.


replace

void replace(javax.swing.text.DocumentFilter.FilterBypass fb,
             int offset,
             int length,
             String string,
             AttributeSet attr)
       throws BadLocationException
Overriden to toggle the value if the positive/minus sign is inserted.

Overrides:
replace in class InternationalFormatter
BadLocationException

toggleSignIfNecessary

private boolean toggleSignIfNecessary(javax.swing.text.DocumentFilter.FilterBypass fb,
                                      int offset,
                                      char aChar)
                               throws BadLocationException
Will change the sign of the integer or exponent field if aChar is the positive or minus sign. Returns true if a sign change was attempted.

BadLocationException

isOnlyIntegerField

private boolean isOnlyIntegerField(int offset,
                                   int length)
Returns true if the range offset to length identifies the only integer field.


toggleSign

private Object toggleSign(boolean positive)
                   throws java.text.ParseException
Invoked to toggle the sign. For this to work the value class must have a single arg constructor that takes a String.

java.text.ParseException

toggleExponentSign

private Object toggleExponentSign(int offset,
                                  char aChar)
                           throws BadLocationException,
                                  java.text.ParseException
Invoked to toggle the sign of the exponent (for scientific numbers).

BadLocationException
java.text.ParseException


comments?