DefaultFormatter.java 12.9 KB
Newer Older
Tom Tromey committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/* DefaultFormatter.java --
Copyright (C) 2005  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath 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 for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package javax.swing.text;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.text.ParseException;

import javax.swing.JFormattedTextField;

/**
 * The <code>DefaultFormatter</code> is a concrete formatter for use in
 * {@link JFormattedTextField}s.
 *
 * It can format arbitrary values by invoking
 * their {@link Object#toString} method.
 *
 * In order to convert a String back to
 * a value, the value class must provide a single argument constructor that
 * takes a String object as argument value. If no such constructor is found,
 * the String itself is passed back by #stringToValue.
 *  
 * @author Roman Kennke (roman@kennke.org)
 */
60
public class DefaultFormatter extends JFormattedTextField.AbstractFormatter
Tom Tromey committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  implements Cloneable, Serializable
{

  /**
   * A {@link DocumentFilter} that intercepts modification of the
   * JFormattedTextField's Document and commits the value depending
   * on the value of the <code>commitsOnValidEdit</code> property.
   *
   */
  // FIXME: Handle allowsInvalid and overwriteMode properties
  private class FormatterDocumentFilter
    extends DocumentFilter
  {
    /**
     * Invoked when text is removed from a text component.
     *
     * @param bypass the FilterBypass to use to mutate the document
     * @param offset the start position of the modification
     * @param length the length of the removed text
     *
     * @throws BadLocationException if offset or lenght are invalid in
     *     the Document
     */
    public void remove(DocumentFilter.FilterBypass bypass, int offset,
                        int length)
      throws BadLocationException
    {
      super.remove(bypass, offset, length);
      checkValidInput();
      commitIfAllowed();
    }
    
    /**
     * Invoked when text is inserted into a text component.
     *
     * @param bypass the FilterBypass to use to mutate the document
     * @param offset the start position of the modification
     * @param text the inserted text
     * @param attributes the attributes of the inserted text
     *
     * @throws BadLocationException if offset or lenght are invalid in
     *     the Document
     */
    public void insertString(DocumentFilter.FilterBypass bypass, int offset,
                              String text, AttributeSet attributes)
      throws BadLocationException
    {
      if (overwriteMode == true)
        replace(bypass, offset, text.length(), text, attributes);
      else
        super.insertString(bypass, offset, text, attributes);
      checkValidInput();
      commitIfAllowed();
    }

    /**
     * Invoked when text is replaced in a text component.
     * 
     * @param bypass the FilterBypass to use to mutate the document
     * @param offset the start position of the modification
     * @param length the length of the removed text
     * @param text the inserted text
     * @param attributes the attributes of the inserted text
     *
     * @throws BadLocationException if offset or lenght are invalid in
     *     the Document
     */
    public void replace(DocumentFilter.FilterBypass bypass, int offset,
                         int length, String text, AttributeSet attributes)
      throws BadLocationException
    {
      super.replace(bypass, offset, length, text, attributes);
      checkValidInput();
      commitIfAllowed();
    }

    /**
     * Commits the value to the JTextTextField if the property
     * <code>commitsOnValidEdit</code> is set to <code>true</code>.
     */
    private void commitIfAllowed()
    {
      if (commitsOnValidEdit == true)
        try
          {
            getFormattedTextField().commitEdit();
          }
        catch (ParseException ex)
          {
            // ignore invalid edits
          }
    }

    /**
     * Checks if the value in the input field is valid. If the
     * property allowsInvalid is set to <code>false</code>, then
     * the string in the input field is not allowed to be entered.
     */
    private void checkValidInput()
    {
      JFormattedTextField ftf = getFormattedTextField();
      try
        {
          Object newval = stringToValue(ftf.getText());
        }
      catch (ParseException ex)
        {
          if (!allowsInvalid)
            {
              // roll back the input if invalid edits are not allowed
              try
                {
                  ftf.setText(valueToString(ftf.getValue()));
                }
              catch (ParseException pe)
                {
                  // if that happens, something serious must be wrong
178 179 180 181
                  AssertionError ae;
		  ae = new AssertionError("values must be parseable");
		  ae.initCause(pe);
		  throw ae;
Tom Tromey committed
182 183 184 185 186 187
                }
            }
        }
    }
  }

188 189
  /** The serialization UID (compatible with JDK1.5). */
  private static final long serialVersionUID = -355018354457785329L;
Tom Tromey committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218

  /**
   * Indicates if the value should be committed after every
   * valid modification of the Document.
   */
  boolean commitsOnValidEdit;

  /**
   * If <code>true</code> newly inserted characters overwrite existing
   * values, otherwise insertion is done the normal way.
   */
  boolean overwriteMode;

  /**
   * If <code>true</code> invalid edits are allowed for a limited
   * time.
   */
  boolean allowsInvalid;

  /**
   * The class that is used for values.
   */
  Class valueClass;

  /**
   * Creates a new instance of <code>DefaultFormatter</code>.
   */
  public DefaultFormatter()
  {
219
    commitsOnValidEdit = false;
Tom Tromey committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    overwriteMode = true;
    allowsInvalid = true;
  }

  /**
   * Installs the formatter on the specified {@link JFormattedTextField}.
   *
   * This method does the following things:
   * <ul>
   * <li>Display the value of #valueToString in the
   *  <code>JFormattedTextField</code></li>
   * <li>Install the Actions from #getActions on the <code>JTextField</code>
   * </li>
   * <li>Install the DocumentFilter returned by #getDocumentFilter</li>
   * <li>Install the NavigationFilter returned by #getNavigationFilter</li>
   * </ul>
   *
   * This method is typically not overridden by subclasses. Instead override
   * one of the mentioned methods in order to customize behaviour.
   *
   * @param ftf the {@link JFormattedTextField} in which this formatter
   *     is installed 
   */
  public void install(JFormattedTextField ftf)
  {
    super.install(ftf);
  }

  /**
   * Returns <code>true</code> if the value should be committed after
   * each valid modification of the input field, <code>false</code> if
   * it should never be committed by this formatter.
   *
   * @return the state of the <code>commitsOnValidEdit</code> property
   *
   * @see #setCommitsOnValidEdit
   */
  public boolean getCommitsOnValidEdit()
  {
    return commitsOnValidEdit;
  }

  /**
   * Sets the value of the <code>commitsOnValidEdit</code> property.
   *
   * @param commitsOnValidEdit the new state of the
   *     <code>commitsOnValidEdit</code> property
   *
   * @see #getCommitsOnValidEdit
   */
  public void setCommitsOnValidEdit(boolean commitsOnValidEdit)
  {
    this.commitsOnValidEdit = commitsOnValidEdit;
  }

  /**
   * Returns the value of the <code>overwriteMode</code> property.
   * If that is set to <code>true</code> then newly inserted characters
   * overwrite existing values, otherwise the characters are inserted like
   * normal. The default is <code>true</code>.
   *
   * @return the value of the <code>overwriteMode</code> property
   */
  public boolean getOverwriteMode()
  {
    return overwriteMode;
  }

  /**
   * Sets the value of the <code>overwriteMode</code> property.
   * 
   * If that is set to <code>true</code> then newly inserted characters
   * overwrite existing values, otherwise the characters are inserted like
   * normal. The default is <code>true</code>.
   *
   * @param overwriteMode the new value for the <code>overwriteMode</code>
   *     property
   */
  public void setOverwriteMode(boolean overwriteMode)
  {
    this.overwriteMode = overwriteMode;
  }

  /**
   * Returns whether or not invalid edits are allowed or not. If invalid
   * edits are allowed, the JFormattedTextField may temporarily contain invalid
   * characters.
   *
   * @return the value of the allowsInvalid property
   */
  public boolean getAllowsInvalid()
  {
    return allowsInvalid;
  }

  /**
   * Sets the value of the <code>allowsInvalid</code> property.
   *
   * @param allowsInvalid the new value for the property
   *
   * @see #getAllowsInvalid()
   */
  public void setAllowsInvalid(boolean allowsInvalid)
  {
    this.allowsInvalid = allowsInvalid;
  }

  /**
   * Returns the class that is used for values. When Strings are converted
   * back to values, this class is used to create new value objects.
   *
   * @return the class that is used for values
   */
333
  public Class<?> getValueClass()
Tom Tromey committed
334 335 336 337 338 339 340 341 342 343 344
  {
    return valueClass;
  }

  /**
   * Sets the class that is used for values.
   *
   * @param valueClass the class that is used for values
   *
   * @see #getValueClass()
   */
345
  public void setValueClass(Class<?> valueClass)
Tom Tromey committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
  {
    this.valueClass = valueClass;
  }

  /**
   * Converts a String (from the JFormattedTextField input) to a value.
   * In order to achieve this, the formatter tries to instantiate an object
   * of the class returned by #getValueClass() using a single argument
   * constructor that takes a String argument. If such a constructor cannot
   * be found, the String itself is returned.
   *
   * @param string the string to convert
   *
   * @return the value for the string
   *
   * @throws ParseException if the string cannot be converted into
   *     a value object (e.g. invalid input)
   */
  public Object stringToValue(String string)
    throws ParseException
  {
    Object value = string;
    Class valueClass = getValueClass();
    if (valueClass == null)
370 371 372 373 374
      {
        JFormattedTextField jft = getFormattedTextField();
        if (jft != null)
          valueClass = jft.getValue().getClass();
      }
Tom Tromey committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    if (valueClass != null)
      try
        {
          Constructor constr = valueClass.getConstructor
                                             (new Class[]{String.class});
          value = constr.newInstance(new Object[]{ string });
        }
      catch (NoSuchMethodException ex)
        {
          // leave value as string
        }
      catch (Exception ex)
        {
          throw new ParseException(string, 0);
        }
    return value;
  }

  /**
   * Converts a value object into a String. This is done by invoking the
   * {@link Object#toString()} method on the value.
   *
   * @param value the value to be converted
   *
   * @return the string representation of the value
   *
   * @throws ParseException if the value cannot be converted
   */
  public String valueToString(Object value)
    throws ParseException
  {
406 407
    if (value == null)
      return "";
Tom Tromey committed
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    return value.toString();
  }

  /**
   * Creates and returns a clone of this DefaultFormatter.
   *
   * @return a clone of this object
   *
   * @throws CloneNotSupportedException not thrown here
   */
  public Object clone()
    throws CloneNotSupportedException
  {
    return super.clone();
  }

  /**
   * Returns the DocumentFilter that is used to restrict input.
   *
   * @return the DocumentFilter that is used to restrict input
   */
  protected DocumentFilter getDocumentFilter()
  {
    return new FormatterDocumentFilter();
  }
}