1187 lines · 43.3 KB · Java
RawDownload
/* * Copyright (c) 2000, 2006, 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. */package javax.swing; import java.awt.*;import java.awt.event.*;import java.awt.im.InputContext;import java.io.*;import java.text.*;import java.util.*;import javax.swing.UIManager;import javax.swing.event.*;import javax.swing.plaf.UIResource;import javax.swing.text.*; /** * <code>JFormattedTextField</code> extends <code>JTextField</code> adding * support for formatting arbitrary values, as well as retrieving a particular * object once the user has edited the text. The following illustrates * configuring a <code>JFormattedTextField</code> to edit dates: * <pre> *   JFormattedTextField ftf = new JFormattedTextField(); *   ftf.setValue(new Date()); * </pre> * <p> * Once a <code>JFormattedTextField</code> has been created, you can * listen for editing changes by way of adding * a <code>PropertyChangeListener</code> and listening for * <code>PropertyChangeEvent</code>s with the property name <code>value</code>. * <p> * <code>JFormattedTextField</code> allows * configuring what action should be taken when focus is lost. The possible * configurations are: * <table summary="Possible JFormattedTextField configurations and their descriptions"> * <tr><th><p align="left">Value</p></th><th><p align="left">Description</p></th></tr> * <tr><td>JFormattedTextField.REVERT *            <td>Revert the display to match that of <code>getValue</code>, *                possibly losing the current edit. *        <tr><td>JFormattedTextField.COMMIT *            <td>Commits the current value. If the value being edited *                isn't considered a legal value by the *                <code>AbstractFormatter</code> that is, a *                <code>ParseException</code> is thrown, then the value *                will not change, and then edited value will persist. *        <tr><td>JFormattedTextField.COMMIT_OR_REVERT *            <td>Similar to <code>COMMIT</code>, but if the value isn't *                legal, behave like <code>REVERT</code>. *        <tr><td>JFormattedTextField.PERSIST *            <td>Do nothing, don't obtain a new *                <code>AbstractFormatter</code>, and don't update the value. * </table> * The default is <code>JFormattedTextField.COMMIT_OR_REVERT</code>, * refer to {@link #setFocusLostBehavior} for more information on this. * <p> * <code>JFormattedTextField</code> allows the focus to leave, even if * the currently edited value is invalid. To lock the focus down while the * <code>JFormattedTextField</code> is an invalid edit state * you can attach an <code>InputVerifier</code>. The following code snippet * shows a potential implementation of such an <code>InputVerifier</code>: * <pre> * public class FormattedTextFieldVerifier extends InputVerifier { *     public boolean verify(JComponent input) { *         if (input instanceof JFormattedTextField) { *             JFormattedTextField ftf = (JFormattedTextField)input; *             AbstractFormatter formatter = ftf.getFormatter(); *             if (formatter != null) { *                 String text = ftf.getText(); *                 try { *                      formatter.stringToValue(text); *                      return true; *                  } catch (ParseException pe) { *                      return false; *                  } *              } *          } *          return true; *      } *      public boolean shouldYieldFocus(JComponent input) { *          return verify(input); *      } *  } * </pre> * <p> * Alternatively, you could invoke <code>commitEdit</code>, which would also * commit the value. * <p> * <code>JFormattedTextField</code> does not do the formatting it self, * rather formatting is done through an instance of * <code>JFormattedTextField.AbstractFormatter</code> which is obtained from * an instance of <code>JFormattedTextField.AbstractFormatterFactory</code>. * Instances of <code>JFormattedTextField.AbstractFormatter</code> are * notified when they become active by way of the * <code>install</code> method, at which point the * <code>JFormattedTextField.AbstractFormatter</code> can install whatever * it needs to, typically a <code>DocumentFilter</code>. Similarly when * <code>JFormattedTextField</code> no longer * needs the <code>AbstractFormatter</code>, it will invoke * <code>uninstall</code>. * <p> * <code>JFormattedTextField</code> typically * queries the <code>AbstractFormatterFactory</code> for an * <code>AbstractFormat</code> when it gains or loses focus. Although this * can change based on the focus lost policy. If the focus lost * policy is <code>JFormattedTextField.PERSIST</code> * and the <code>JFormattedTextField</code> has been edited, the * <code>AbstractFormatterFactory</code> will not be queried until the * value has been commited. Similarly if the focus lost policy is * <code>JFormattedTextField.COMMIT</code> and an exception * is thrown from <code>stringToValue</code>, the * <code>AbstractFormatterFactory</code> will not be querired when focus is * lost or gained. * <p> * <code>JFormattedTextField.AbstractFormatter</code> * is also responsible for determining when values are commited to * the <code>JFormattedTextField</code>. Some * <code>JFormattedTextField.AbstractFormatter</code>s will make new values * available on every edit, and others will never commit the value. You can * force the current value to be obtained * from the current <code>JFormattedTextField.AbstractFormatter</code> * by way of invoking <code>commitEdit</code>. <code>commitEdit</code> will * be invoked whenever return is pressed in the * <code>JFormattedTextField</code>. * <p> * If an <code>AbstractFormatterFactory</code> has not been explicitly * set, one will be set based on the <code>Class</code> of the value type after * <code>setValue</code> has been invoked (assuming value is non-null). * For example, in the following code an appropriate * <code>AbstractFormatterFactory</code> and <code>AbstractFormatter</code> * will be created to handle formatting of numbers: * <pre> *   JFormattedTextField tf = new JFormattedTextField(); *   tf.setValue(new Number(100)); * </pre> * <p> * <strong>Warning:</strong> As the <code>AbstractFormatter</code> will * typically install a <code>DocumentFilter</code> on the * <code>Document</code>, and a <code>NavigationFilter</code> on the * <code>JFormattedTextField</code> you should not install your own. If you do, * you are likely to see odd behavior in that the editing policy of the * <code>AbstractFormatter</code> will not be enforced. * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <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<sup><font size="-2">TM</font></sup> * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @since 1.4 */public class JFormattedTextField extends JTextField {    private static final String uiClassID = "FormattedTextFieldUI";    private static final Action[] defaultActions =            { new CommitAction(), new CancelAction() };     /**     * Constant identifying that when focus is lost,     * <code>commitEdit</code> should be invoked. If in commiting the     * new value a <code>ParseException</code> is thrown, the invalid     * value will remain.     *     * @see #setFocusLostBehavior     */    public static final int COMMIT = 0;     /**     * Constant identifying that when focus is lost,     * <code>commitEdit</code> should be invoked. If in commiting the new     * value a <code>ParseException</code> is thrown, the value will be     * reverted.     *     * @see #setFocusLostBehavior     */    public static final int COMMIT_OR_REVERT = 1;     /**     * Constant identifying that when focus is lost, editing value should     * be reverted to current value set on the     * <code>JFormattedTextField</code>.     *     * @see #setFocusLostBehavior     */    public static final int REVERT = 2;     /**     * Constant identifying that when focus is lost, the edited value     * should be left.     *     * @see #setFocusLostBehavior     */    public static final int PERSIST = 3;      /**     * Factory used to obtain an instance of AbstractFormatter.     */    private AbstractFormatterFactory factory;    /**     * Object responsible for formatting the current value.     */    private AbstractFormatter format;    /**     * Last valid value.     */    private Object value;    /**     * True while the value being edited is valid.     */    private boolean editValid;    /**     * Behavior when focus is lost.     */    private int focusLostBehavior;    /**     * Indicates the current value has been edited.     */    private boolean edited;    /**     * Used to set the dirty state.     */    private DocumentListener documentListener;    /**     * Masked used to set the AbstractFormatterFactory.     */    private Object mask;    /**     * ActionMap that the TextFormatter Actions are added to.     */    private ActionMap textFormatterActionMap;    /**     * Indicates the input method composed text is in the document     */    private boolean composedTextExists = false;    /**     * A handler for FOCUS_LOST event     */    private FocusLostHandler focusLostHandler;      /**     * Creates a <code>JFormattedTextField</code> with no     * <code>AbstractFormatterFactory</code>. Use <code>setMask</code> or     * <code>setFormatterFactory</code> to configure the     * <code>JFormattedTextField</code> to edit a particular type of     * value.     */    public JFormattedTextField() {        super();        enableEvents(AWTEvent.FOCUS_EVENT_MASK);        setFocusLostBehavior(COMMIT_OR_REVERT);    }     /**     * Creates a JFormattedTextField with the specified value. This will     * create an <code>AbstractFormatterFactory</code> based on the     * type of <code>value</code>.     *     * @param value Initial value for the JFormattedTextField     */    public JFormattedTextField(Object value) {        this();        setValue(value);    }     /**     * Creates a <code>JFormattedTextField</code>. <code>format</code> is     * wrapped in an appropriate <code>AbstractFormatter</code> which is     * then wrapped in an <code>AbstractFormatterFactory</code>.     *     * @param format Format used to look up an AbstractFormatter     */    public JFormattedTextField(java.text.Format format) {        this();        setFormatterFactory(getDefaultFormatterFactory(format));    }     /**     * Creates a <code>JFormattedTextField</code> with the specified     * <code>AbstractFormatter</code>. The <code>AbstractFormatter</code>     * is placed in an <code>AbstractFormatterFactory</code>.     *     * @param formatter AbstractFormatter to use for formatting.     */    public JFormattedTextField(AbstractFormatter formatter) {        this(new DefaultFormatterFactory(formatter));    }     /**     * Creates a <code>JFormattedTextField</code> with the specified     * <code>AbstractFormatterFactory</code>.     *     * @param factory AbstractFormatterFactory used for formatting.     */    public JFormattedTextField(AbstractFormatterFactory factory) {        this();        setFormatterFactory(factory);    }     /**     * Creates a <code>JFormattedTextField</code> with the specified     * <code>AbstractFormatterFactory</code> and initial value.     *     * @param factory <code>AbstractFormatterFactory</code> used for     *        formatting.     * @param currentValue Initial value to use     */    public JFormattedTextField(AbstractFormatterFactory factory,                               Object currentValue) {        this(currentValue);        setFormatterFactory(factory);    }     /**     * Sets the behavior when focus is lost. This will be one of     * <code>JFormattedTextField.COMMIT_OR_REVERT</code>,     * <code>JFormattedTextField.REVERT</code>,     * <code>JFormattedTextField.COMMIT</code> or     * <code>JFormattedTextField.PERSIST</code>     * Note that some <code>AbstractFormatter</code>s may push changes as     * they occur, so that the value of this will have no effect.     * <p>     * This will throw an <code>IllegalArgumentException</code> if the object     * passed in is not one of the afore mentioned values.     * <p>     * The default value of this property is     * <code>JFormattedTextField.COMMIT_OR_REVERT</code>.     *     * @param behavior Identifies behavior when focus is lost     * @throws IllegalArgumentException if behavior is not one of the known     *         values     * @beaninfo     *  enum: COMMIT         JFormattedTextField.COMMIT     *        COMMIT_OR_REVERT JFormattedTextField.COMMIT_OR_REVERT     *        REVERT         JFormattedTextField.REVERT     *        PERSIST        JFormattedTextField.PERSIST     *  description: Behavior when component loses focus     */    public void setFocusLostBehavior(int behavior) {        if (behavior != COMMIT && behavior != COMMIT_OR_REVERT &&            behavior != PERSIST && behavior != REVERT) {            throw new IllegalArgumentException("setFocusLostBehavior must be one of: JFormattedTextField.COMMIT, JFormattedTextField.COMMIT_OR_REVERT, JFormattedTextField.PERSIST or JFormattedTextField.REVERT");        }        focusLostBehavior = behavior;    }     /**     * Returns the behavior when focus is lost. This will be one of     * <code>COMMIT_OR_REVERT</code>,     * <code>COMMIT</code>,     * <code>REVERT</code> or     * <code>PERSIST</code>     * Note that some <code>AbstractFormatter</code>s may push changes as     * they occur, so that the value of this will have no effect.     *     * @return returns behavior when focus is lost     */    public int getFocusLostBehavior() {        return focusLostBehavior;    }     /**     * Sets the <code>AbstractFormatterFactory</code>.     * <code>AbstractFormatterFactory</code> is     * able to return an instance of <code>AbstractFormatter</code> that is     * used to format a value for display, as well an enforcing an editing     * policy.     * <p>     * If you have not explicitly set an <code>AbstractFormatterFactory</code>     * by way of this method (or a constructor) an     * <code>AbstractFormatterFactory</code> and consequently an     * <code>AbstractFormatter</code> will be used based on the     * <code>Class</code> of the value. <code>NumberFormatter</code> will     * be used for <code>Number</code>s, <code>DateFormatter</code> will     * be used for <code>Dates</code>, otherwise <code>DefaultFormatter</code>     * will be used.     * <p>     * This is a JavaBeans bound property.     *     * @param tf <code>AbstractFormatterFactory</code> used to lookup     *          instances of <code>AbstractFormatter</code>     * @beaninfo     *       bound: true     *   attribute: visualUpdate true     * description: AbstractFormatterFactory, responsible for returning an     *              AbstractFormatter that can format the current value.     */    public void setFormatterFactory(AbstractFormatterFactory tf) {        AbstractFormatterFactory oldFactory = factory;         factory = tf;        firePropertyChange("formatterFactory", oldFactory, tf);        setValue(getValue(), true, false);    }     /**     * Returns the current <code>AbstractFormatterFactory</code>.     *     * @see #setFormatterFactory     * @return <code>AbstractFormatterFactory</code> used to determine     *         <code>AbstractFormatter</code>s     */    public AbstractFormatterFactory getFormatterFactory() {        return factory;    }     /**     * Sets the current <code>AbstractFormatter</code>.     * <p>     * You should not normally invoke this, instead set the     * <code>AbstractFormatterFactory</code> or set the value.     * <code>JFormattedTextField</code> will     * invoke this as the state of the <code>JFormattedTextField</code>     * changes and requires the value to be reset.     * <code>JFormattedTextField</code> passes in the     * <code>AbstractFormatter</code> obtained from the     * <code>AbstractFormatterFactory</code>.     * <p>     * This is a JavaBeans bound property.     *     * @see #setFormatterFactory     * @param format AbstractFormatter to use for formatting     * @beaninfo     *       bound: true     *   attribute: visualUpdate true     * description: TextFormatter, responsible for formatting the current value     */    protected void setFormatter(AbstractFormatter format) {        AbstractFormatter oldFormat = this.format;         if (oldFormat != null) {            oldFormat.uninstall();        }        setEditValid(true);        this.format = format;        if (format != null) {            format.install(this);        }        setEdited(false);        firePropertyChange("textFormatter", oldFormat, format);    }     /**     * Returns the <code>AbstractFormatter</code> that is used to format and     * parse the current value.     *     * @return AbstractFormatter used for formatting     */    public AbstractFormatter getFormatter() {        return format;    }     /**     * Sets the value that will be formatted by an     * <code>AbstractFormatter</code> obtained from the current     * <code>AbstractFormatterFactory</code>. If no     * <code>AbstractFormatterFactory</code> has been specified, this will     * attempt to create one based on the type of <code>value</code>.     * <p>     * The default value of this property is null.     * <p>     * This is a JavaBeans bound property.     *     * @param value Current value to display     * @beaninfo     *       bound: true     *   attribute: visualUpdate true     * description: The value to be formatted.     */    public void setValue(Object value) {        if (value != null && getFormatterFactory() == null) {            setFormatterFactory(getDefaultFormatterFactory(value));

Lines 1–500 of 1187.