javax.swing.text
Class InternationalFormatter

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

public class InternationalFormatter
extends DefaultFormatter

Safe: InternationalFormatter extends DefaultFormatter, using an instance of java.text.Format to handle the conversion to a String, and the conversion from a String.

If getAllowsInvalid() is false, this will ask the Format to format the current text on every edit.

You can specify a minimum and maximum value by way of the setMinimum and setMaximum methods. In order for this to work the values returned from stringToValue must be comparable to the min/max values by way of the Comparable interface.

Be careful how you configure the Format and the InternationalFormatter, as it is possible to create a situation where certain values can not be input. Consider the date format 'M/d/yy', an InternationalFormatter that is always valid (setAllowsInvalid(false)), is in overwrite mode (setOverwriteMode(true)) 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'.

If InternationalFormatter is configured to only allow valid values (setAllowsInvalid(false)), every valid edit will result in the text of the JFormattedTextField being completely reset from the Format. The cursor position will also be adjusted as literal characters are added/removed from the resulting String.

InternationalFormatter's behavior of stringToValue is slightly different than that of DefaultTextFormatter, it does the following:

  1. parseObject is invoked on the Format specified by setFormat
  2. If a Class has been set for the values (setValueClass), supers implementation is invoked to convert the value returned from parseObject to the appropriate class.
  3. If a ParseException has not been thrown, and the value is outside the min/max a ParseException is thrown.
  4. The value is returned.
InternationalFormatter implements stringToValue in this manner so that you can specify an alternate Class than Format may return.

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.7 04/09/01
See Also:
java.text.Format, java.lang.Comparable, Serialized Form

Field Summary
private static java.text.Format.Field[] EMPTY_FIELD_ARRAY
          Used by getFields.
private  java.text.Format format
          Object used to handle the conversion.
private  boolean ignoreDocumentMutate
          If true, DocumentFilter methods are unconditionally allowed, and no checking is done on their values.
private  java.text.AttributedCharacterIterator iterator
          Used to iterate over characters.
private  BitSet literalMask
          A bit is set for every index identified in the AttributedCharacterIterator that is not considered decoration.
private  Comparable max
          Can be used to impose a maximum value.
private  Comparable min
          Can be used to impose a minimum value.
private  String string
          Current value being displayed.
private  boolean validMask
          True if the Format was able to convert the value to a String and back.
 
Fields inherited from class javax.swing.text.DefaultFormatter
replaceHolder
 
Fields inherited from class javax.swing.AbstractFormatter
 
Constructor Summary
InternationalFormatter()
          Enabled: Creates an InternationalFormatter with no Format specified.
InternationalFormatter(java.text.Format format)
          Enabled: Creates an InternationalFormatter with the specified Format instance.
 
Method Summary
(package private)  Object adjustValue(Object value, Map attributes, Object field, int direction)
          Subclasses supporting incrementing must override this to handle the actual incrementing.
(package private)  boolean canIncrement(Object field, int cursorPosition)
          Returns true if field is non-null.
(package private)  boolean canReplace(javax.swing.text.DefaultFormatter.ReplaceHolder rh)
          Overriden in an attempt to honor the literals.
 Object clone()
          Suppressed: Creates a copy of the DefaultFormatter.
protected  Action[] getActions()
          If getSupportsIncrement returns true, this returns two Actions suitable for incrementing/decrementing the value.
(package private)  Object getAdjustField(int start, Map attributes)
          Returns the field that will be adjusted by adjustValue.
(package private)  Map getAttributes(int index)
          Returns a Set of the attribute identifiers at index.
(package private)  int getAttributeStart(java.text.AttributedCharacterIterator.Attribute id)
          Returns the start of the first run that contains the attribute id.
(package private)  char getBufferedChar(int index)
          Returns the character from the mask that has been buffered at index.
 java.text.Format.Field[] getFields(int offset)
          Enabled: Returns the Format.Field constants associated with the text at offset.
private  int getFieldTypeCountTo(Object f, int start)
          Returns the number of occurences of f before the location start in the current AttributedCharacterIterator.
 java.text.Format getFormat()
          Enabled: Returns the format that dictates the legal values that can be edited and displayed.
(package private)  java.text.AttributedCharacterIterator getIterator()
          Returns the AttributedCharacterIterator used to format the last value.
(package private)  char getLiteral(int index)
          Returns the literal character at index.
(package private)  int getLiteralCountTo(int index)
          Returns the number of literal characters before index.
 Comparable getMaximum()
          Enabled: Returns the maximum permissible value.
 Comparable getMinimum()
          Enabled: Returns the minimum permissible value.
private  int getNextNonliteralIndex(int index, int direction)
          Returns the index of the next non-literal character starting at index.
(package private)  javax.swing.text.DefaultFormatter.ReplaceHolder getReplaceHolder(javax.swing.text.DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
          Overriden to return an instance of ExtendedReplaceHolder.
(package private)  boolean getSupportsIncrement()
          Returns false, indicating InternationalFormatter does not allow incrementing of the value.
 void install(JFormattedTextField ftf)
          Enabled: Installs the DefaultFormatter onto a particular JFormattedTextField.
(package private)  boolean isLiteral(int index)
          Returns true if the character at index is a literal, that is not editable.
(package private)  boolean isLiteral(Map attributes)
          Returns true if attributes is null or empty.
(package private)  boolean isNavigatable(int offset)
          Returns true if the character at offset is navigatable too.
(package private)  boolean isValidMask()
          Returns true if the current mask is valid.
(package private)  boolean isValidValue(Object value, boolean wantsCCE)
          Returns true if value is between the min/max.
private  void readObject(ObjectInputStream s)
          Subclassed to update the internal representation of the mask after the default read operation has completed.
(package private)  boolean replace(javax.swing.text.DefaultFormatter.ReplaceHolder rh)
          When in !allowsInvalid mode the text is reset on every edit, thus supers implementation will position the cursor at the wrong position.
(package private)  void replace(javax.swing.text.DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
          Overriden to unconditionally allow the replace if ignoreDocumentMutate is true.
private  void repositionCursor(int startLiteralCount, int end, int direction)
          Repositions the cursor.
(package private)  void resetValue(Object value)
          Resets the value of the JFormattedTextField to be value.
(package private)  void selectField(Object f, int count)
          Selects the fields identified by attributes.
 void setFormat(java.text.Format format)
          Enabled: Sets the format that dictates the legal values that can be edited and displayed.
 void setMaximum(Comparable max)
          Enabled: Sets the maximum permissible value.
 void setMinimum(Comparable minimum)
          Enabled: Sets the minimum permissible value.
 Object stringToValue(String text)
          Suppressed: Returns the Object representation of the String text.
(package private)  Object stringToValue(String text, java.text.Format f)
          Invokes parseObject on f, returning its value.
(package private)  void updateMask()
          Updates the AttributedCharacterIterator by invoking formatToCharacterIterator on the Format.
private  void updateMask(java.text.AttributedCharacterIterator iterator)
          Updates the interal bitset from iterator.
(package private)  void updateMaskIfNecessary()
          Updates the AttributedCharacterIterator and bitset, if necessary.
(package private)  void updateValue(Object value)
          Overriden to update the mask after invoking supers implementation.
 String valueToString(Object value)
          Suppressed: Returns a String representation of the Object value.
 
Methods inherited from class javax.swing.text.DefaultFormatter
commitEdit, getAllowsInvalid, getCommitsOnValidEdit, getDocumentFilter, getInitialVisualPosition, getNavigationFilter, getNextCursorPosition, getNextVisualPositionFrom, getOverwriteMode, getReplaceString, getValueClass, isLegalInsertText, 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

EMPTY_FIELD_ARRAY

private static final java.text.Format.Field[] EMPTY_FIELD_ARRAY
Used by getFields.


format

private java.text.Format format
Object used to handle the conversion.


max

private Comparable max
Can be used to impose a maximum value.


min

private Comparable min
Can be used to impose a minimum value.


literalMask

private transient BitSet literalMask
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.


iterator

private transient java.text.AttributedCharacterIterator iterator
Used to iterate over characters.


validMask

private transient boolean validMask
True if the Format was able to convert the value to a String and back.


string

private transient String string
Current value being displayed.


ignoreDocumentMutate

private transient boolean ignoreDocumentMutate
If true, DocumentFilter methods are unconditionally allowed, and no checking is done on their values. This is used when incrementing/decrementing via the actions.

Constructor Detail

InternationalFormatter

public InternationalFormatter()
Enabled: Creates an InternationalFormatter with no Format specified.


InternationalFormatter

public InternationalFormatter(java.text.Format format)
Enabled: Creates an InternationalFormatter with the specified Format instance.

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.

Parameters:
format - Format instance used for converting from/to Strings

getFormat

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

Returns:
Format instance used for converting from/to Strings

setMinimum

public void setMinimum(Comparable minimum)
Enabled: Sets the minimum permissible value. If the valueClass has not been specified, and minimum is non null, the valueClass will be set to that of the class of minimum.

Parameters:
minimum - Minimum legal value that can be input
See Also:
DefaultFormatter.setValueClass(java.lang.Class)

getMinimum

public Comparable getMinimum()
Enabled: Returns the minimum permissible value.

Returns:
Minimum legal value that can be input

setMaximum

public void setMaximum(Comparable max)
Enabled: Sets the maximum permissible value. If the valueClass has not been specified, and max is non null, the valueClass will be set to that of the class of max.

See Also:
DefaultFormatter.setValueClass(java.lang.Class)

getMaximum

public Comparable getMaximum()
Enabled: Returns the maximum permissible value.

Returns:
Maximum legal value that can be input

install

public void install(JFormattedTextField ftf)
Enabled: Installs the DefaultFormatter onto a particular JFormattedTextField. This will invoke valueToString to convert the current value from the JFormattedTextField to a String. This will then install the Actions from getActions, the DocumentFilter returned from getDocumentFilter and the NavigationFilter returned from getNavigationFilter onto the JFormattedTextField.

Subclasses will typically only need to override this if they wish to install additional listeners on the JFormattedTextField.

If there is a ParseException in converting the current value to a String, this will set the text to an empty String, and mark the JFormattedTextField as being in an invalid state.

While this is a public method, this is typically only useful for subclassers of JFormattedTextField. JFormattedTextField will invoke this method at the appropriate times when the value changes, or its internal state changes.

Overrides:
install in class DefaultFormatter
Parameters:
ftf - JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.

valueToString

public String valueToString(Object value)
                     throws java.text.ParseException
Suppressed: Returns a String representation of the Object value. This invokes format on the current Format.

Overrides:
valueToString in class DefaultFormatter
Parameters:
value - Value to convert
Returns:
String representation of value
Throws:
ParseException - if there is an error in the conversion

stringToValue

public Object stringToValue(String text)
                     throws java.text.ParseException
Suppressed: Returns the Object representation of the String text.

Overrides:
stringToValue in class DefaultFormatter
Parameters:
text - String to convert
Returns:
Object representation of text
Throws:
ParseException - if there is an error in the conversion

getFields

public java.text.Format.Field[] getFields(int offset)
Enabled: Returns the Format.Field constants associated with the text at offset. If offset is not a valid location into the current text, this will return an empty array.

Parameters:
offset - offset into text to be examined
Returns:
Format.Field constants associated with the text at the given position.

clone

public Object clone()
             throws CloneNotSupportedException
Suppressed: Creates a copy of the DefaultFormatter.

Overrides:
clone in class DefaultFormatter
Returns:
copy of the DefaultFormatter
CloneNotSupportedException

getActions

protected Action[] getActions()
If getSupportsIncrement returns true, this returns two Actions suitable for incrementing/decrementing the value.

Overrides:
getActions in class javax.swing.JFormattedTextField.AbstractFormatter
Returns:
Array of Actions to install on JFormattedTextField

stringToValue

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

java.text.ParseException

isValidValue

boolean isValidValue(Object value,
                     boolean wantsCCE)
Returns true if value is between the min/max.

Parameters:
wantsCCE - If false, and a ClassCastException is thrown in comparing the values, the exception is consumed and false is returned.

getAttributes

Map getAttributes(int index)
Returns a Set of the attribute identifiers at index.


getAttributeStart

int getAttributeStart(java.text.AttributedCharacterIterator.Attribute id)
Returns the start of the first run that contains the attribute id. This will return -1 if the attribute can not be found.


getIterator

java.text.AttributedCharacterIterator getIterator()
Returns the AttributedCharacterIterator used to format the last value.


updateMaskIfNecessary

void updateMaskIfNecessary()
Updates the AttributedCharacterIterator and bitset, if necessary.


updateMask

void updateMask()
Updates the AttributedCharacterIterator by invoking formatToCharacterIterator on the Format. If this is successful, updateMask(AttributedCharacterIterator) is then invoked to update the internal bitmask.


getLiteralCountTo

int getLiteralCountTo(int index)
Returns the number of literal characters before index.


isLiteral

boolean isLiteral(int index)
Returns true if the character at index is a literal, that is not editable.


getLiteral

char getLiteral(int index)
Returns the literal character at index.


isNavigatable

boolean isNavigatable(int offset)
Returns true if the character at offset is navigatable too. This is implemented in terms of isLiteral, subclasses may wish to provide different behavior.

Overrides:
isNavigatable in class DefaultFormatter

updateValue

void updateValue(Object value)
Overriden to update the mask after invoking supers implementation.

Overrides:
updateValue in class DefaultFormatter

replace

void replace(javax.swing.text.DocumentFilter.FilterBypass fb,
             int offset,
             int length,
             String text,
             AttributeSet attrs)
       throws BadLocationException
Overriden to unconditionally allow the replace if ignoreDocumentMutate is true.

Overrides:
replace in class DefaultFormatter
BadLocationException

getNextNonliteralIndex

private int getNextNonliteralIndex(int index,
                                   int direction)
Returns the index of the next non-literal character starting at index. If index is not a literal, it will be returned.

Parameters:
direction - Amount to increment looking for non-literal

canReplace

boolean canReplace(javax.swing.text.DefaultFormatter.ReplaceHolder rh)
Overriden in an attempt to honor the literals.

If we do not allow invalid values and are in overwrite mode, this does the following for each character in the replacement range:

  1. If the character is a literal, add it to the string to replace with. If there is text to insert and it doesn't match the literal, then insert the literal in the the middle of the insert text. This allows you to either paste in literals or not and get the same behavior.
  2. If there is no text to insert, replace it with ' '.
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.

Overrides:
canReplace in class DefaultFormatter

replace

boolean replace(javax.swing.text.DefaultFormatter.ReplaceHolder rh)
          throws BadLocationException
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 repositionCursor to correctly reset the cursor.

Overrides:
replace in class DefaultFormatter
BadLocationException

repositionCursor

private void repositionCursor(int startLiteralCount,
                              int end,
                              int direction)
Repositions the cursor. startLiteralCount 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 end to position the cursor from.


getBufferedChar

char getBufferedChar(int index)
Returns the character from the mask that has been buffered at index.


isValidMask

boolean isValidMask()
Returns true if the current mask is valid.


isLiteral

boolean isLiteral(Map attributes)
Returns true if attributes is null or empty.


updateMask

private void updateMask(java.text.AttributedCharacterIterator iterator)
Updates the interal bitset from iterator. This will set validMask to true if iterator is non-null.


canIncrement

boolean canIncrement(Object field,
                     int cursorPosition)
Returns true if field is non-null. Subclasses that wish to allow incrementing to happen outside of the known fields will need to override this.


selectField

void selectField(Object f,
                 int count)
Selects the fields identified by attributes.


getAdjustField

Object getAdjustField(int start,
                      Map attributes)
Returns the field that will be adjusted by adjustValue.


getFieldTypeCountTo

private int getFieldTypeCountTo(Object f,
                                int start)
Returns the number of occurences of f before the location start in the current AttributedCharacterIterator.


adjustValue

Object adjustValue(Object value,
                   Map attributes,
                   Object field,
                   int direction)
             throws BadLocationException,
                    java.text.ParseException
Subclasses supporting incrementing must override this to handle the actual incrementing. value is the current value, attributes gives the field the cursor is in (may be null depending upon canIncrement) and direction is the amount to increment by.

BadLocationException
java.text.ParseException

getSupportsIncrement

boolean getSupportsIncrement()
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 adjustValue.


resetValue

void resetValue(Object value)
          throws BadLocationException,
                 java.text.ParseException
Resets the value of the JFormattedTextField to be value.

BadLocationException
java.text.ParseException

readObject

private void readObject(ObjectInputStream s)
                 throws IOException,
                        ClassNotFoundException
Subclassed to update the internal representation of the mask after the default read operation has completed.

IOException
ClassNotFoundException

getReplaceHolder

javax.swing.text.DefaultFormatter.ReplaceHolder getReplaceHolder(javax.swing.text.DocumentFilter.FilterBypass fb,
                                                                 int offset,
                                                                 int length,
                                                                 String text,
                                                                 AttributeSet attrs)
Overriden to return an instance of ExtendedReplaceHolder.

Overrides:
getReplaceHolder in class DefaultFormatter


comments?