FileDocCategorySizeDatePackage
DefaultFormatter.javaAPI DocJava SE 5 API25509Fri Aug 26 14:58:14 BST 2005javax.swing.text

DefaultFormatter

public class DefaultFormatter extends JFormattedTextField$AbstractFormatter implements Serializable, Cloneable
DefaultFormatter formats aribtrary objects. Formatting is done by invoking the toString method. In order to convert the value back to a String, your class must provide a constructor that takes a String argument. If no single argument constructor that takes a String is found, the returned value will be the String passed into stringToValue.

Instances of DefaultFormatter can not be used in multiple instances of JFormattedTextField. To obtain a copy of an already configured DefaultFormatter, use the clone method.

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 {@link java.beans.XMLEncoder}.

see
javax.swing.JFormattedTextField.AbstractFormatter
version
1.13 05/05/04
since
1.4

Fields Summary
private boolean
allowsInvalid
Indicates if the value being edited must match the mask.
private boolean
overwriteMode
If true, editing mode is in overwrite (or strikethough).
private boolean
commitOnEdit
If true, any time a valid edit happens commitEdit is invoked.
private Class
valueClass
Class used to create new instances.
private NavigationFilter
navigationFilter
NavigationFilter that forwards calls back to DefaultFormatter.
private DocumentFilter
documentFilter
DocumentFilter that forwards calls back to DefaultFormatter.
transient ReplaceHolder
replaceHolder
Used during replace to track the region to replace.
Constructors Summary
public DefaultFormatter()
Creates a DefaultFormatter.

        overwriteMode = true;
        allowsInvalid = true;
    
Methods Summary
booleancanReplace(javax.swing.text.DefaultFormatter$ReplaceHolder rh)
Returns true if the edit described by rh will result in a legal value.

        return isValidEdit(rh);
    
public java.lang.Objectclone()
Creates a copy of the DefaultFormatter.

return
copy of the DefaultFormatter

        DefaultFormatter formatter = (DefaultFormatter)super.clone();

        formatter.navigationFilter = null;
        formatter.documentFilter = null;
        formatter.replaceHolder = null;
        return formatter;
    
voidcommitEdit()
Invokes commitEdit on the JFormattedTextField.

        JFormattedTextField ftf = getFormattedTextField();

        if (ftf != null) {
            ftf.commitEdit();
        }
    
public booleangetAllowsInvalid()
Returns whether or not the value being edited is allowed to be invalid for a length of time.

return
false if the edited value must always be valid

        return allowsInvalid;
    
public booleangetCommitsOnValidEdit()
Returns when edits are published back to the JFormattedTextField.

return
true if edits are commited after evey valid edit

        return commitOnEdit;
    
protected javax.swing.text.DocumentFiltergetDocumentFilter()
Returns the DocumentFilter used to restrict the characters that can be input into the JFormattedTextField.

return
DocumentFilter to restrict edits

        if (documentFilter == null) {
            documentFilter = new DefaultDocumentFilter();
        }
        return documentFilter;
    
intgetInitialVisualPosition()
Returns the initial location to position the cursor at. This forwards the call to getNextNavigatableChar.

        return getNextNavigatableChar(0, 1);
    
protected javax.swing.text.NavigationFiltergetNavigationFilter()
Returns the NavigationFilter used to restrict where the cursor can be placed.

return
NavigationFilter to restrict navigation

        if (navigationFilter == null) {
            navigationFilter = new DefaultNavigationFilter();
        }
        return navigationFilter;
    
intgetNextCursorPosition(int offset, int direction)
Returns the next cursor position from offset by incrementing direction. This uses getNextNavigatableChar as well as constraining the location to the max position.

        int newOffset = getNextNavigatableChar(offset, direction);
        int max = getFormattedTextField().getDocument().getLength();

        if (!getAllowsInvalid()) {
            if (direction == -1 && offset == newOffset) {
                // Case where hit backspace and only characters before
                // offset are fixed.
                newOffset = getNextNavigatableChar(newOffset, 1);
                if (newOffset >= max) {
                    newOffset = offset;
                }
            }
            else if (direction == 1 && newOffset >= max) {
                // Don't go beyond last editable character.
                newOffset = getNextNavigatableChar(max - 1, -1);
                if (newOffset < max) {
                    newOffset++;
                }
            }
        }
        return newOffset;
    
private intgetNextNavigatableChar(int offset, int direction)
Returns the next editable character starting at offset incrementing the offset by direction.

        int max = getFormattedTextField().getDocument().getLength();

        while (offset >= 0 && offset < max) {
            if (isNavigatable(offset)) {
                return offset;
            }
            offset += direction;
        }
        return offset;
    
intgetNextVisualPositionFrom(javax.swing.text.JTextComponent text, int pos, javax.swing.text.Position$Bias bias, int direction, javax.swing.text.Position$Bias[] biasRet)
Finds the next navigatable character.

        int value = text.getUI().getNextVisualPositionFrom(text, pos, bias,
                                                           direction, biasRet);

        if (value == -1) {
            return -1;
        }
        if (!getAllowsInvalid() && (direction == SwingConstants.EAST ||
                                    direction == SwingConstants.WEST)) {
            int last = -1;

            while (!isNavigatable(value) && value != last) {
                last = value;
                value = text.getUI().getNextVisualPositionFrom(
                              text, value, bias, direction,biasRet);
            }
            int max = getFormattedTextField().getDocument().getLength();
            if (last == value || value == max) {
                if (value == 0) {
                    biasRet[0] = Position.Bias.Forward;
                    value = getInitialVisualPosition();
                }
                if (value >= max && max > 0) {
                    // Pending: should not assume forward!
                    biasRet[0] = Position.Bias.Forward;
                    value = getNextNavigatableChar(max - 1, -1) + 1;
                }
            }
        }
        return value;
    
public booleangetOverwriteMode()
Returns the behavior when inserting characters.

return
true if newly inserted characters overwrite existing characters

        return overwriteMode;
    
javax.swing.text.DefaultFormatter$ReplaceHoldergetReplaceHolder(javax.swing.text.DocumentFilter$FilterBypass fb, int offset, int length, java.lang.String text, javax.swing.text.AttributeSet attrs)
Returns the ReplaceHolder to track the replace of the specified text.

        if (replaceHolder == null) {
            replaceHolder = new ReplaceHolder();
        }
        replaceHolder.reset(fb, offset, length, text, attrs);
        return replaceHolder;
    
java.lang.StringgetReplaceString(int offset, int deleteLength, java.lang.String replaceString)
A convenience methods to return the result of deleting deleteLength characters at offset and inserting replaceString at offset in the current text field.

        String string = getFormattedTextField().getText();
        String result;

        result = string.substring(0, offset);
        if (replaceString != null) {
            result += replaceString;
        }
        if (offset + deleteLength < string.length()) {
            result += string.substring(offset + deleteLength);
        }
        return result;
    
public java.lang.ClassgetValueClass()
Returns that class that is used to create new Objects.

return
Class used to constuct return value from stringToValue

        return valueClass;
    
public voidinstall(javax.swing.JFormattedTextField ftf)
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.

param
ftf JFormattedTextField to format for, may be null indicating uninstall from current JFormattedTextField.

        super.install(ftf);
        positionCursorAtInitialLocation();
    
booleanisLegalInsertText(java.lang.String text)
Returns true if the text in text can be inserted. This does not mean the text will ultimately be inserted, it is used if text can trivially reject certain characters.

        return true;
    
booleanisNavigatable(int offset)
Subclasses should override this if they want cursor navigation to skip certain characters. A return value of false indicates the character at offset should be skipped when navigating throught the field.

        return true;
    
booleanisValidEdit(javax.swing.text.DefaultFormatter$ReplaceHolder rh)

        if (!getAllowsInvalid()) {
            String newString = getReplaceString(rh.offset, rh.length, rh.text);

            try {
                rh.value = stringToValue(newString);

                return true;
            } catch (ParseException pe) {
                return false;
            }
        }
        return true;
    
voidmoveDot(javax.swing.text.NavigationFilter$FilterBypass fb, int dot, javax.swing.text.Position$Bias bias)
NavigationFilter method, subclasses that wish finer control should override this.

        fb.moveDot(dot, bias);
    
voidpositionCursorAtInitialLocation()
Positions the cursor at the initial location.

        JFormattedTextField ftf = getFormattedTextField();
        if (ftf != null) {
            ftf.setCaretPosition(getInitialVisualPosition());
        }
    
voidreplace(javax.swing.text.DocumentFilter$FilterBypass fb, int offset, int length, java.lang.String text, javax.swing.text.AttributeSet attrs)
DocumentFilter method, funnels into replace.

        ReplaceHolder rh = getReplaceHolder(fb, offset, length, text, attrs);

        replace(rh);
    
booleanreplace(javax.swing.text.DefaultFormatter$ReplaceHolder rh)
If the edit described by rh is legal, this will return true, commit the edit (if necessary) and update the cursor position. This forwards to canReplace and isLegalInsertText as necessary to determine if the edit is in fact legal.

All of the DocumentFilter methods funnel into here, you should generally only have to override this.

        boolean valid = true;
        int direction = 1;

        if (rh.length > 0 && (rh.text == null || rh.text.length() == 0) &&
               (getFormattedTextField().getSelectionStart() != rh.offset ||
                   rh.length > 1)) {
            direction = -1;
        }

        if (getOverwriteMode() && rh.text != null) {
            rh.length = Math.min(Math.max(rh.length, rh.text.length()),
                                 rh.fb.getDocument().getLength() - rh.offset);
        }
        if ((rh.text != null && !isLegalInsertText(rh.text)) ||
            !canReplace(rh) ||
            (rh.length == 0 && (rh.text == null || rh.text.length() == 0))) {
            valid = false;
        }
        if (valid) {
            int cursor = rh.cursorPosition;

            rh.fb.replace(rh.offset, rh.length, rh.text, rh.attrs);
            if (cursor == -1) {
                cursor = rh.offset;
                if (direction == 1 && rh.text != null) {
                    cursor = rh.offset + rh.text.length();
                }
            }
            updateValue(rh.value);
            repositionCursor(cursor, direction);
            return true;
        }
        else {
            invalidEdit();
        }
        return false;
    
voidrepositionCursor(int offset, int direction)
Resets the cursor by using getNextCursorPosition.

        getFormattedTextField().getCaret().setDot(getNextCursorPosition
                                                  (offset, direction));
    
public voidsetAllowsInvalid(boolean allowsInvalid)
Sets whether or not the value being edited is allowed to be invalid for a length of time (that is, stringToValue throws a ParseException). It is often convenient to allow the user to temporarily input an invalid value.

param
allowsInvalid Used to indicate if the edited value must always be valid

        this.allowsInvalid = allowsInvalid;
    
public voidsetCommitsOnValidEdit(boolean commit)
Sets when edits are published back to the JFormattedTextField. If true, commitEdit is invoked after every valid edit (any time the text is edited). On the other hand, if this is false than the DefaultFormatter does not publish edits back to the JFormattedTextField. As such, the only time the value of the JFormattedTextField will change is when commitEdit is invoked on JFormattedTextField, typically when enter is pressed or focus leaves the JFormattedTextField.

param
commit Used to indicate when edits are commited back to the JTextComponent

        commitOnEdit = commit;
    
voidsetDot(javax.swing.text.NavigationFilter$FilterBypass fb, int dot, javax.swing.text.Position$Bias bias)
NavigationFilter method, subclasses that wish finer control should override this.

        fb.setDot(dot, bias);
    
public voidsetOverwriteMode(boolean overwriteMode)
Configures the behavior when inserting characters. If overwriteMode is true (the default), new characters overwrite existing characters in the model.

param
overwriteMode Indicates if overwrite or overstrike mode is used

        this.overwriteMode = overwriteMode;
    
public voidsetValueClass(java.lang.Class valueClass)
Sets that class that is used to create new Objects. If the passed in class does not have a single argument constructor that takes a String, String values will be used.

param
valueClass Class used to construct return value from stringToValue

        this.valueClass = valueClass;
    
public java.lang.ObjectstringToValue(java.lang.String string)
Converts the passed in String into an instance of getValueClass by way of the constructor that takes a String argument. If getValueClass returns null, the Class of the current value in the JFormattedTextField will be used. If this is null, a String will be returned. If the constructor thows an exception, a ParseException will be thrown. If there is no single argument String constructor, string will be returned.

throws
ParseException if there is an error in the conversion
param
string String to convert
return
Object representation of text

        Class vc = getValueClass();
        JFormattedTextField ftf = getFormattedTextField();

        if (vc == null && ftf != null) {
            Object value = ftf.getValue();

            if (value != null) {
                vc = value.getClass();
            }
        }
        if (vc != null) {
            Constructor cons;

            try {
                cons = vc.getConstructor(new Class[] { String.class });

            } catch (NoSuchMethodException nsme) {
                cons = null;
            }

            if (cons != null) {
                try {
                    return cons.newInstance(new Object[] { string });
                } catch (Throwable ex) {
                    throw new ParseException("Error creating instance", 0);
                }
            }
        }
        return string;
    
voidupdateValue()
Pushes the value to the JFormattedTextField if the current value is valid and invokes setEditValid based on the validity of the value.

        updateValue(null);
    
voidupdateValue(java.lang.Object value)
Pushes the value to the editor if we are to commit on edits. If value is null, the current value will be obtained from the text component.

        try {
            if (value == null) {
                String string = getFormattedTextField().getText();

                value = stringToValue(string);
            }

            if (getCommitsOnValidEdit()) {
                commitEdit();
            }
            setEditValid(true);
        } catch (ParseException pe) {
            setEditValid(false);
        }
    
public java.lang.StringvalueToString(java.lang.Object value)
Converts the passed in Object into a String by way of the toString method.

throws
ParseException if there is an error in the conversion
param
value Value to convert
return
String representation of value

        if (value == null) {
            return "";
        }
        return value.toString();