javax.swing

Class JTextArea

Implemented Interfaces:
Accessible, ImageObserver, MenuContainer, Scrollable, Serializable

public class JTextArea
extends JTextComponent

The JTextArea 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 java.awt.TextArea component, which provides similar functionality using native widgets.

This component has additional functionality to the AWT class. It follows the same design pattern as seen in other text components, such as JTextField, JTextPane and JEditorPane, and embodied in JTextComponent. These classes separate the text (the model) from its appearance within the onscreen component (the view). The text is held within a javax.swing.text.Document 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 DocumentEvents delivered to registered DocumentListeners, rather than this component.

Unlike java.awt.TextArea, JTextArea does not handle scrolling. Instead, this functionality is delegated to a JScrollPane, 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 rows and columns properties are used in calculating the preferred size of the scroll pane's view port.

See Also:
TextArea, JTextComponent, JTextField, JTextPane, JEditorPane, Document, DocumentEvent, DocumentListener, Serialized Form

Nested Class Summary

protected class
JTextArea.AccessibleJTextArea
Provides accessibility support for JTextArea.

Nested classes/interfaces inherited from class javax.swing.text.JTextComponent

JTextComponent.AccessibleJTextComponent, JTextComponent.KeyBinding

Nested classes/interfaces inherited from class javax.swing.JComponent

JComponent.AccessibleJComponent

Nested classes/interfaces inherited from class java.awt.Container

Container.AccessibleAWTContainer

Nested classes/interfaces inherited from class java.awt.Component

Component.AccessibleAWTComponent, Component.BltBufferStrategy, Component.FlipBufferStrategy

Field Summary

Fields inherited from class javax.swing.text.JTextComponent

DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY

Fields inherited from class javax.swing.JComponent

TOOL_TIP_TEXT_KEY, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW, accessibleContext, listenerList, ui

Fields inherited from class java.awt.Component

BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT

Fields inherited from interface java.awt.image.ImageObserver

ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH

Constructor Summary

JTextArea()
Creates a new JTextArea object.
JTextArea(int rows, int columns)
Creates a new JTextArea object.
JTextArea(String text)
Creates a new JTextArea object.
JTextArea(String text, int rows, int columns)
Creates a new JTextArea object.
JTextArea(Document doc)
Creates a new JTextArea object.
JTextArea(Document doc, String text, int rows, int columns)
Creates a new JTextArea object.

Method Summary

void
append(String toAppend)
Appends the supplied text to the current contents of the document model.
protected Document
createDefaultModel()
Creates the default document model.
AccessibleContext
getAccessibleContext()
Returns the accessible context associated with the JTextArea.
protected int
getColumnWidth()
int
getColumns()
Returns the current number of columns.
int
getLineCount()
int
getLineEndOffset(int line)
int
getLineOfOffset(int offset)
int
getLineStartOffset(int line)
boolean
getLineWrap()
Checks whether line wrapping is enabled.
Dimension
getPreferredScrollableViewportSize()
Returns the preferred size of that text component in the case it is embedded within a JScrollPane.
Dimension
getPreferredSize()
Returns the preferred size for the JTextArea.
protected int
getRowHeight()
int
getRows()
Returns the current number of rows.
boolean
getScrollableTracksViewportWidth()
Returns true if the width of this component should be forced to match the width of a surrounding view port.
int
getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the increment that is needed to expose exactly one new line of text.
int
getTabSize()
Returns the number of characters used for a tab.
String
getUIClassID()
Returns the UI class ID string.
boolean
getWrapStyleWord()
Checks whether word style wrapping is enabled.
void
insert(String string, int position)
Inserts the supplied text at the specified position.
void
replaceRange(String text, int start, int end)
void
setColumns(int columns)
Sets the number of rows.
void
setLineWrap(boolean flag)
Enables/disables line wrapping.
void
setRows(int rows)
Sets the number of rows.
void
setTabSize(int newSize)
Sets the number of characters used for a tab to the supplied value.
void
setWrapStyleWord(boolean flag)
Enables/Disables word style wrapping.

Methods inherited from class javax.swing.text.JTextComponent

addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getAccessibleContext, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getFocusAccelerator, getHighlighter, getInputMethodListeners, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, getUIClassID, isEditable, loadKeymap, modelToView, moveCaretPosition, paramString, paste, read, removeCaretListener, removeInputMethodListener, removeKeymap, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setDisabledTextColor, setDocument, setDragEnabled, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, write

Methods inherited from class javax.swing.JComponent

addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, extends EventListener> T[] getListeners, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setNextFocusableComponent, setOpaque, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI

Methods inherited from class java.awt.Container

add, add, add, add, add, addContainerListener, addImpl, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, extends EventListener> T[] getListeners, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponentZOrder, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, paramString, preferredSize, print, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeNotify, setComponentZOrder, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, setLayout, transferFocusDownCycle, update, validate, validateTree

Methods inherited from class java.awt.Component

action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, disableEvents, dispatchEvent, doLayout, enable, enable, enableEvents, enableInputMethods, extends EventListener> T[] getListeners, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getAlignmentX, getAlignmentY, getBackground, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, invalidate, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFocusable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paint, paintAll, paramString, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, processComponentEvent, processEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFocusable, setFont, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle, update, validate

Methods inherited from class java.lang.Object

clone, equals, extends Object> getClass, finalize, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

JTextArea

public JTextArea()
Creates a new JTextArea object.

JTextArea

public JTextArea(int rows,
                 int columns)
Creates a new JTextArea object.
Parameters:
rows - the number of rows
columns - the number of cols
Throws:
IllegalArgumentException - if rows or columns are negative

JTextArea

public JTextArea(String text)
Creates a new JTextArea object.
Parameters:
text - the initial text

JTextArea

public JTextArea(String text,
                 int rows,
                 int columns)
Creates a new JTextArea object.
Parameters:
text - the initial text
rows - the number of rows
columns - the number of cols
Throws:
IllegalArgumentException - if rows or columns are negative

JTextArea

public JTextArea(Document doc)
Creates a new JTextArea object.
Parameters:
doc - the document model to use

JTextArea

public JTextArea(Document doc,
                 String text,
                 int rows,
                 int columns)
Creates a new JTextArea object.
Parameters:
doc - the document model to use
text - the initial text
rows - the number of rows
columns - the number of cols
Throws:
IllegalArgumentException - if rows or columns are negative

Method Details

append

public void append(String toAppend)
Appends the supplied text to the current contents of the document model.
Parameters:
toAppend - the text to append

createDefaultModel

protected Document createDefaultModel()
Creates the default document model.
Returns:
a new default model

getAccessibleContext

public AccessibleContext getAccessibleContext()
Returns the accessible context associated with the JTextArea.
Specified by:
getAccessibleContext in interface Accessible
Overrides:
getAccessibleContext in interface JTextComponent
Returns:
the accessible context associated with the JTextArea

getColumnWidth

protected int getColumnWidth()

getColumns

public int getColumns()
Returns the current number of columns.
Returns:
number of columns

getLineCount

public int getLineCount()

getLineEndOffset

public int getLineEndOffset(int line)
            throws BadLocationException

getLineOfOffset

public int getLineOfOffset(int offset)
            throws BadLocationException

getLineStartOffset

public int getLineStartOffset(int line)
            throws BadLocationException

getLineWrap

public boolean getLineWrap()
Checks whether line wrapping is enabled.
Returns:
true if line wrapping is enabled, false otherwise

getPreferredScrollableViewportSize

public Dimension getPreferredScrollableViewportSize()
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.
Specified by:
getPreferredScrollableViewportSize in interface Scrollable
Overrides:
getPreferredScrollableViewportSize in interface JTextComponent
Returns:
the preferred size of that text component in the case it is embedded within a JScrollPane

getPreferredSize

public Dimension getPreferredSize()
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 getColumns() and getRows().
Overrides:
getPreferredSize in interface JComponent
Returns:
the preferred size of the JTextArea

getRowHeight

protected int getRowHeight()

getRows

public int getRows()
Returns the current number of rows.
Returns:
number of rows

getScrollableTracksViewportWidth

public boolean getScrollableTracksViewportWidth()
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.
Specified by:
getScrollableTracksViewportWidth in interface Scrollable
Overrides:
getScrollableTracksViewportWidth in interface JTextComponent
Returns:
true if lines are wrapped.

getScrollableUnitIncrement

public int getScrollableUnitIncrement(Rectangle visibleRect,
                                      int orientation,
                                      int direction)
Returns the increment that is needed to expose exactly one new line of text. This is implemented here to return the values of getRowHeight() and getColumnWidth(), depending on the value of the argument direction.
Specified by:
getScrollableUnitIncrement in interface Scrollable
Overrides:
getScrollableUnitIncrement in interface JTextComponent
Parameters:
visibleRect - the view area that is visible in the viewport
orientation - either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL
direction - less than zero for up/left scrolling, greater than zero for down/right scrolling
Returns:
the increment that is needed to expose exactly one new row or column of text
Throws:
IllegalArgumentException - if orientation is invalid

getTabSize

public int getTabSize()
Returns the number of characters used for a tab. This defaults to 8.
Returns:
the current number of spaces used for a tab.

getUIClassID

public String getUIClassID()
Returns the UI class ID string.
Overrides:
getUIClassID in interface JTextComponent
Returns:
the string "TextAreaUI"

getWrapStyleWord

public boolean getWrapStyleWord()
Checks whether word style wrapping is enabled.
Returns:
true if word style wrapping is enabled, false otherwise

insert

public void insert(String string,
                   int position)
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.
Parameters:
string - The string of text to insert.
position - The position at which to insert the supplied text.
Throws:
IllegalArgumentException - if the position is < 0 or greater than the length of the current text.

replaceRange

public void replaceRange(String text,
                         int start,
                         int end)

setColumns

public void setColumns(int columns)
Sets the number of rows.
Parameters:
columns - number of columns
Throws:
IllegalArgumentException - if columns is negative

setLineWrap

public void setLineWrap(boolean flag)
Enables/disables line wrapping.
Parameters:
flag - true to enable line wrapping, false otherwise

setRows

public void setRows(int rows)
Sets the number of rows.
Parameters:
rows - number of rows
Throws:
IllegalArgumentException - if rows is negative

setTabSize

public void setTabSize(int newSize)
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.
Parameters:
newSize - The new number of characters to use for a tab.

setWrapStyleWord

public void setWrapStyleWord(boolean flag)
Enables/Disables word style wrapping.
Parameters:
flag - true to enable word style wrapping, false otherwise

JTextArea.java -- 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.