JTextArea.java 17 KB
Newer Older
1
/* JTextArea.java --
Tom Tromey committed
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
   Copyright (C) 2004, 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;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Rectangle;

45 46
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleStateSet;
Tom Tromey committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.text.View;

/**
 * The <code>JTextArea</code> component provides a multi-line area for displaying
 * and editing plain text.  The component is designed to act as a lightweight
 * replacement for the heavyweight <code>java.awt.TextArea</code> component,
 * which provides similar functionality using native widgets.
 * <p>
 *
 * This component has additional functionality to the AWT class.  It follows
 * the same design pattern as seen in other text components, such as
 * <code>JTextField</code>, <code>JTextPane</code> and <code>JEditorPane</code>,
 * and embodied in <code>JTextComponent</code>.  These classes separate the text
 * (the model) from its appearance within the onscreen component (the view).  The
 * text is held within a <code>javax.swing.text.Document</code> object, which can
 * also maintain relevant style information where necessary.  As a result, it is the
 * document that should be monitored for textual changes, via
 * <code>DocumentEvent</code>s delivered to registered
 * <code>DocumentListener</code>s, rather than this component.
 * <p>
 *
 * Unlike <code>java.awt.TextArea</code>, <code>JTextArea</code> does not
 * handle scrolling.  Instead, this functionality is delegated to a
 * <code>JScrollPane</code>, which can contain the text area and handle
 * scrolling when required.  Likewise, the word wrapping functionality
 * of the AWT component is converted to a property of this component
 * and the <code>rows</code> and <code>columns</code> properties
 * are used in calculating the preferred size of the scroll pane's
 * view port.
 *
 * @author Michael Koch  (konqueror@gmx.de)
 * @author Andrew John Hughes  (gnu_andrew@member.fsf.org)
 * @see java.awt.TextArea
Tom Tromey committed
85
 * @see javax.swing.text.JTextComponent
Tom Tromey committed
86 87 88 89
 * @see javax.swing.JTextField
 * @see javax.swing.JTextPane
 * @see javax.swing.JEditorPane
 * @see javax.swing.text.Document
Tom Tromey committed
90 91
 * @see javax.swing.event.DocumentEvent
 * @see javax.swing.event.DocumentListener
Tom Tromey committed
92 93 94 95 96
 */

public class JTextArea extends JTextComponent
{
  /**
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
   * Provides accessibility support for <code>JTextArea</code>.
   *
   * @author Roman Kennke (kennke@aicas.com)
   */
  protected class AccessibleJTextArea extends AccessibleJTextComponent
  {

    /**
     * Creates a new <code>AccessibleJTextArea</code> object.
     */
    protected AccessibleJTextArea()
    {
      super();
    }

    /**
     * Returns the accessible state of this <code>AccessibleJTextArea</code>.
     *
     * @return  the accessible state of this <code>AccessibleJTextArea</code>
     */
    public AccessibleStateSet getAccessibleStateSet()
    {
      AccessibleStateSet state = super.getAccessibleStateSet();
      // TODO: Figure out what state must be added here to the super's state.
      return state;
    }
  }

  /**
Tom Tromey committed
126 127 128
   * Compatible with Sun's JDK
   */
  private static final long serialVersionUID = -6141680179310439825L;
129

Tom Tromey committed
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  /**
   * The number of rows used by the component.
   */
  private int rows;

  /**
   * The number of columns used by the component.
   */
  private int columns;

  /**
   * Whether line wrapping is enabled or not.
   */
  private boolean lineWrap;

  /**
   * The number of characters equal to a tab within the text.
   */
  private int tabSize = 8;

  private boolean wrapStyleWord;

  /**
   * Creates a new <code>JTextArea</code> object.
   */
  public JTextArea()
  {
    this(null, null, 0, 0);
  }

  /**
   * Creates a new <code>JTextArea</code> object.
   *
   * @param text the initial text
   */
  public JTextArea(String text)
  {
    this(null, text, 0, 0);
  }

  /**
   * Creates a new <code>JTextArea</code> object.
   *
   * @param rows the number of rows
   * @param columns the number of cols
   *
   * @exception IllegalArgumentException if rows or columns are negative
   */
  public JTextArea(int rows, int columns)
  {
    this(null, null, rows, columns);
  }

  /**
   * Creates a new <code>JTextArea</code> object.
   *
   * @param text the initial text
   * @param rows the number of rows
   * @param columns the number of cols
   *
   * @exception IllegalArgumentException if rows or columns are negative
   */
  public JTextArea(String text, int rows, int columns)
  {
    this(null, text, rows, columns);
  }

  /**
   * Creates a new <code>JTextArea</code> object.
   *
Tom Tromey committed
200
   * @param doc the document model to use
Tom Tromey committed
201 202 203 204 205 206 207 208 209
   */
  public JTextArea(Document doc)
  {
    this(doc, null, 0, 0);
  }

  /**
   * Creates a new <code>JTextArea</code> object.
   *
Tom Tromey committed
210
   * @param doc the document model to use
Tom Tromey committed
211 212 213 214 215 216 217 218 219
   * @param text the initial text
   * @param rows the number of rows
   * @param columns the number of cols
   *
   * @exception IllegalArgumentException if rows or columns are negative
   */
  public JTextArea(Document doc, String text, int rows, int columns)
  {
    setDocument(doc == null ? createDefaultModel() : doc);
220 221 222 223 224
    // Only explicitly setText() when there is actual text since
    // setText() might be overridden and not expected to be called
    // from the constructor (as in JEdit).
    if (text != null)
      setText(text);
Tom Tromey committed
225 226 227 228 229 230 231 232 233 234 235 236 237
    setRows(rows);
    setColumns(columns);
  }

  /**
   * Appends the supplied text to the current contents
   * of the document model.
   *
   * @param toAppend the text to append
   */
  public void append(String toAppend)
  {
      try
238 239 240
          {
              getDocument().insertString(getText().length(), toAppend, null);
          }
Tom Tromey committed
241
      catch (BadLocationException exception)
242 243 244 245
          {
              /* This shouldn't happen in theory -- but, if it does...  */
              throw new RuntimeException("Unexpected exception occurred.", exception);
          }
246 247
      if (toAppend != null && toAppend.length() > 0)
        revalidate();
Tom Tromey committed
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
  }

  /**
   * Creates the default document model.
   *
   * @return a new default model
   */
  protected Document createDefaultModel()
  {
    return new PlainDocument();
  }

  /**
   * Returns true if the width of this component should be forced
   * to match the width of a surrounding view port.  When line wrapping
   * is turned on, this method returns true.
   *
   * @return true if lines are wrapped.
   */
  public boolean getScrollableTracksViewportWidth()
  {
    return lineWrap ? true : super.getScrollableTracksViewportWidth();
  }

  /**
   * Returns the increment that is needed to expose exactly one new line
   * of text. This is implemented here to return the values of
Tom Tromey committed
275
   * {@link #getRowHeight} and {@link #getColumnWidth}, depending on
Tom Tromey committed
276 277 278
   * the value of the argument <code>direction</code>.
   *
   * @param visibleRect the view area that is visible in the viewport
Tom Tromey committed
279 280
   * @param orientation either {@link SwingConstants#VERTICAL} or
   *     {@link SwingConstants#HORIZONTAL}
Tom Tromey committed
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 333 334 335 336 337 338 339
   * @param direction less than zero for up/left scrolling, greater
   *     than zero for down/right scrolling
   *
   * @return the increment that is needed to expose exactly one new row
   *     or column of text
   *
   * @throws IllegalArgumentException if <code>orientation</code> is invalid
   */
  public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation,
                                        int direction)
  {
    if (orientation == SwingConstants.VERTICAL)
      return getRowHeight();
    else if (orientation == SwingConstants.HORIZONTAL)
      return getColumnWidth();
    else
      throw new IllegalArgumentException("orientation must be either "
                                     + "javax.swing.SwingConstants.VERTICAL "
                                     + "or "
                                     + "javax.swing.SwingConstants.HORIZONTAL"
                                     );
  }

  /**
   * Returns the preferred size of that text component in the case
   * it is embedded within a JScrollPane. This uses the column and
   * row settings if they are explicitly set, or fall back to
   * the superclass's behaviour.
   *
   * @return the preferred size of that text component in the case
   *     it is embedded within a JScrollPane
   */
  public Dimension getPreferredScrollableViewportSize()
  {
    if ((rows > 0) && (columns > 0))
      return new Dimension(columns * getColumnWidth(), rows * getRowHeight());
    else
      return super.getPreferredScrollableViewportSize();
  }

  /**
   * Returns the UI class ID string.
   *
   * @return the string "TextAreaUI"
   */
  public String getUIClassID()
  {
    return "TextAreaUI";
  }

  /**
   * Returns the current number of columns.
   *
   * @return number of columns
   */
  public int getColumns()
  {
    return columns;
  }
340

Tom Tromey committed
341 342 343 344 345 346 347 348 349 350 351
  /**
   * Sets the number of rows.
   *
   * @param columns number of columns
   *
   * @exception IllegalArgumentException if columns is negative
   */
  public void setColumns(int columns)
  {
    if (columns < 0)
      throw new IllegalArgumentException();
352

353 354 355 356 357
    if (columns != this.columns)
      {
        this.columns = columns;
        revalidate();
      }
Tom Tromey committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  }

  /**
   * Returns the current number of rows.
   *
   * @return number of rows
   */
  public int getRows()
  {
    return rows;
  }

  /**
   * Sets the number of rows.
   *
Tom Tromey committed
373
   * @param rows number of rows
Tom Tromey committed
374 375 376 377 378 379 380
   *
   * @exception IllegalArgumentException if rows is negative
   */
  public void setRows(int rows)
  {
    if (rows < 0)
      throw new IllegalArgumentException();
381

382 383 384 385 386
    if (rows != this.rows)
      {
        this.rows = rows;
        revalidate();
      }
Tom Tromey committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  }

  /**
   * Checks whether line wrapping is enabled.
   *
   * @return <code>true</code> if line wrapping is enabled,
   * <code>false</code> otherwise
   */
  public boolean getLineWrap()
  {
    return lineWrap;
  }

  /**
   * Enables/disables line wrapping.
   *
Tom Tromey committed
403
   * @param flag <code>true</code> to enable line wrapping,
Tom Tromey committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
   * <code>false</code> otherwise
   */
  public void setLineWrap(boolean flag)
  {
    if (lineWrap == flag)
      return;

    boolean oldValue = lineWrap;
    lineWrap = flag;
    firePropertyChange("lineWrap", oldValue, lineWrap);
  }

  /**
   * Checks whether word style wrapping is enabled.
   *
   * @return <code>true</code> if word style wrapping is enabled,
   * <code>false</code> otherwise
   */
  public boolean getWrapStyleWord()
  {
    return wrapStyleWord;
  }
426

Tom Tromey committed
427 428 429 430 431 432 433 434 435 436
  /**
   * Enables/Disables word style wrapping.
   *
   * @param flag <code>true</code> to enable word style wrapping,
   * <code>false</code> otherwise
   */
  public void setWrapStyleWord(boolean flag)
  {
    if (wrapStyleWord == flag)
      return;
437

Tom Tromey committed
438 439 440 441
    boolean oldValue = wrapStyleWord;
    wrapStyleWord = flag;
    firePropertyChange("wrapStyleWord", oldValue, wrapStyleWord);
  }
442

Tom Tromey committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  /**
   * Returns the number of characters used for a tab.
   * This defaults to 8.
   *
   * @return the current number of spaces used for a tab.
   */
  public int getTabSize()
  {
    return tabSize;
  }

  /**
   * Sets the number of characters used for a tab to the
   * supplied value.  If a change to the tab size property
   * occurs (i.e. newSize != tabSize), a property change event
   * is fired.
459
   *
Tom Tromey committed
460 461 462 463 464 465
   * @param newSize The new number of characters to use for a tab.
   */
  public void setTabSize(int newSize)
  {
    if (tabSize == newSize)
      return;
466

Tom Tromey committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    int oldValue = tabSize;
    tabSize = newSize;
    firePropertyChange("tabSize", oldValue, tabSize);
  }

  protected int getColumnWidth()
  {
    FontMetrics metrics = getToolkit().getFontMetrics(getFont());
    return metrics.charWidth('m');
  }

  public int getLineCount()
  {
    return getDocument().getDefaultRootElement().getElementCount();
  }

  public int getLineStartOffset(int line)
     throws BadLocationException
  {
    int lineCount = getLineCount();
487

Tom Tromey committed
488 489 490 491 492 493 494 495 496 497 498
    if (line < 0 || line > lineCount)
      throw new BadLocationException("Non-existing line number", line);

    Element lineElem = getDocument().getDefaultRootElement().getElement(line);
    return lineElem.getStartOffset();
  }

  public int getLineEndOffset(int line)
     throws BadLocationException
  {
    int lineCount = getLineCount();
499

Tom Tromey committed
500 501 502 503 504 505 506 507 508 509 510 511 512
    if (line < 0 || line > lineCount)
      throw new BadLocationException("Non-existing line number", line);

    Element lineElem = getDocument().getDefaultRootElement().getElement(line);
    return lineElem.getEndOffset();
  }

  public int getLineOfOffset(int offset)
    throws BadLocationException
  {
    Document doc = getDocument();

    if (offset < doc.getStartPosition().getOffset()
513
        || offset >= doc.getEndPosition().getOffset())
Tom Tromey committed
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
      throw new BadLocationException("offset outside of document", offset);

    return doc.getDefaultRootElement().getElementIndex(offset);
  }

  protected int getRowHeight()
  {
    FontMetrics metrics = getToolkit().getFontMetrics(getFont());
    return metrics.getHeight();
  }

  /**
   * Inserts the supplied text at the specified position.  Nothing
   * happens in the case that the model or the supplied string is null
   * or of zero length.
   *
   * @param string The string of text to insert.
   * @param position The position at which to insert the supplied text.
   * @throws IllegalArgumentException if the position is &lt; 0 or greater
   * than the length of the current text.
   */
  public void insert(String string, int position)
  {
    // Retrieve the document model.
    Document doc = getDocument();
539

Tom Tromey committed
540 541
    // Check the model and string for validity.
    if (doc == null
542 543
        || string == null
        || string.length() == 0)
Tom Tromey committed
544 545 546 547 548
      return;

    // Insert the text into the model.
    try
      {
549
        doc.insertString(position, string, null);
Tom Tromey committed
550 551 552
      }
    catch (BadLocationException e)
      {
553 554
        throw new IllegalArgumentException("The supplied position, "
                                           + position + ", was invalid.");
Tom Tromey committed
555 556 557 558 559 560
      }
  }

  public void replaceRange(String text, int start, int end)
  {
    Document doc = getDocument();
561

Tom Tromey committed
562
    if (start > end
563 564
        || start < doc.getStartPosition().getOffset()
        || end >= doc.getEndPosition().getOffset())
Tom Tromey committed
565 566 567 568 569 570 571 572 573
      throw new IllegalArgumentException();

    try
      {
        doc.remove(start, end - start);
        doc.insertString(start, text, null);
      }
    catch (BadLocationException e)
      {
574
        // This cannot happen as we check offset above.
Tom Tromey committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
      }
  }

  /**
   * Returns the preferred size for the JTextArea. This is the maximum of
   * the size that is needed to display the content and the requested size
   * as per {@link #getColumns} and {@link #getRows}.
   *
   * @return the preferred size of the JTextArea
   */
  public Dimension getPreferredSize()
  {
    int reqWidth = getColumns() * getColumnWidth();
    int reqHeight = getRows() * getRowHeight();
    View view = getUI().getRootView(this);
    int neededWidth = (int) view.getPreferredSpan(View.HORIZONTAL);
    int neededHeight = (int) view.getPreferredSpan(View.VERTICAL);
    return new Dimension(Math.max(reqWidth, neededWidth),
                          Math.max(reqHeight, neededHeight));
  }
595 596 597 598 599 600 601 602 603 604 605 606

  /**
   * Returns the accessible context associated with the <code>JTextArea</code>.
   *
   * @return the accessible context associated with the <code>JTextArea</code>
   */
  public AccessibleContext getAccessibleContext()
  {
    if (accessibleContext == null)
      accessibleContext = new AccessibleJTextArea();
    return accessibleContext;
  }
Tom Tromey committed
607
}