This documentation differs from the official API.
Jadeite adds
extra features to the API including:
variable font sizes,
constructions examples,
placeholders for classes and methods, and auto-generated “See Also” links.
Additionally it
is missing some items found in standard Javadoc documentation, including:
generics type information,
“Deprecated” tags and comments,
“See Also” links,
along with other minor differences.
Please send any questions or feedback to
bam@cs.cmu.edu.
javax.swing
class JTextArea
- All Implemented Interfaces:
- MenuContainer, ImageObserver, Serializable, Accessible, Scrollable, TransferHandler.HasGetTransferHandler
-
Most common ways to construct:
-
JTextArea Reply = new JTextArea(5, 20);
Based on 106 examples
-
-
JTextArea textArea = new JTextArea();
Based on 80 examples
public class JTextArea
extends JTextComponent
A JTextArea
is a multi-line area that displays plain text.
It is intended to be a lightweight component that provides source
compatibility with the java.awt.TextArea
class where it can
reasonably do so.
You can find information and examples of using all the text components in
Using Text Components,
a section in The Java Tutorial.
This component has capabilities not found in the
java.awt.TextArea
class. The superclass should be
consulted for additional capabilities.
Alternative multi-line text classes with
more capabilities are JTextPane
and JEditorPane
.
The java.awt.TextArea
internally handles scrolling.
JTextArea
is different in that it doesn't manage scrolling,
but implements the swing Scrollable
interface. This allows it
to be placed inside a JScrollPane
if scrolling
behavior is desired, and used directly if scrolling is not desired.
The java.awt.TextArea
has the ability to do line wrapping.
This was controlled by the horizontal scrolling policy. Since
scrolling is not done by JTextArea
directly, backward
compatibility must be provided another way. JTextArea
has
a bound property for line wrapping that controls whether or
not it will wrap lines. By default, the line wrapping property
is set to false (not wrapped).
java.awt.TextArea
has two properties rows
and columns
that are used to determine the preferred size.
JTextArea
uses these properties to indicate the
preferred size of the viewport when placed inside a JScrollPane
to match the functionality provided by java.awt.TextArea
.
JTextArea
has a preferred size of what is needed to
display all of the text, so that it functions properly inside of
a JScrollPane
. If the value for rows
or columns
is equal to zero,
the preferred size along that axis is used for
the viewport preferred size along the same axis.
The java.awt.TextArea
could be monitored for changes by adding
a TextListener
for TextEvent
s.
In the JTextComponent
based
components, changes are broadcasted from the model via a
DocumentEvent
to DocumentListeners
.
The DocumentEvent
gives
the location of the change and the kind of change if desired.
The code fragment might look something like:
DocumentListener myListener = ??;
JTextArea myArea = ??;
myArea.getDocument().addDocumentListener(myListener);
- Newlines
-
For a discussion on how newlines are handled, see
DefaultEditorKit.
Warning: Swing is not thread safe. For more
information see Swing's Threading
Policy.
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}.
Nested Class Summary |
protected class |
This class implements accessibility support for the
JTextArea class. |
Constructor Summary |
Constructs a new TextArea.
|
Constructs a new JTextArea with the given document model, and defaults
for all of the other arguments (null, 0, 0).
|
Constructs a new JTextArea with the specified number of rows
and columns, and the given model.
|
Constructs a new empty TextArea with the specified number of
rows and columns.
|
Constructs a new TextArea with the specified text displayed.
|
Constructs a new TextArea with the specified text and number
of rows and columns.
|
Method Summary |
void |
Appends the given text to the end of the document.
|
protected Document |
Creates the default implementation of the model
to be used at construction if one isn't explicitly
given.
|
AccessibleContext |
Gets the AccessibleContext associated with this JTextArea.
|
int |
Returns the number of columns in the TextArea.
|
protected int |
Gets column width.
|
int |
Determines the number of lines contained in the area.
|
int |
Determines the offset of the end of the given line.
|
int |
Translates an offset into the components text to a
line number.
|
int |
Determines the offset of the start of the given line.
|
boolean |
Gets the line-wrapping policy of the text area.
|
Dimension |
Returns the preferred size of the viewport if this component
is embedded in a JScrollPane.
|
Dimension |
Returns the preferred size of the TextArea.
|
protected int |
Defines the meaning of the height of a row.
|
int |
Returns the number of rows in the TextArea.
|
boolean |
Returns true if a viewport should always force the width of this
Scrollable to match the width of the viewport.
|
int |
Components that display logical rows or columns should compute
the scroll increment that will completely expose one new row
or column, depending on the value of orientation.
|
int |
Gets the number of characters used to expand tabs.
|
String |
Returns the class ID for the UI.
|
boolean |
Gets the style of wrapping used if the text area is wrapping
lines.
|
void |
Inserts the specified text at the specified position.
|
protected String |
Returns a string representation of this JTextArea.
|
void |
Replaces text from the indicated start to end position with the
new text specified.
|
void |
Sets the number of columns for this TextArea.
|
void |
Sets the current font.
|
void |
Sets the line-wrapping policy of the text area.
|
void |
Sets the number of rows for this TextArea.
|
void |
Sets the number of characters to expand tabs to.
|
void |
Sets the style of wrapping used if the text area is wrapping
lines.
|
Methods inherited from class javax.swing.text.JTextComponent |
addCaretListener, addInputMethodListener, addKeymap, copy, cut, fireCaretUpdate, getAccessibleContext, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPreferredScrollableViewportSize, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, moveCaretPosition, paramString, paste, print, print, print, processInputMethodEvent, read, removeCaretListener, removeKeymap, removeNotify, replaceSelection, select, selectAll, setCaret, setCaretColor, setCaretPosition, setComponentOrientation, setDisabledTextColor, setDocument, setDragEnabled, setDropMode, 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, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, 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, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, 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, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getListeners, 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, transferFocusBackward, 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, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getAlignmentX, getAlignmentY, getBackground, getBaseline, getBaselineResizeBehavior, 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, getListeners, 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, isFocusable, isFocusCycleRoot, isFocusOwner, isFocusTraversable, 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, setFocusable, setFocusTraversalKeys, setFocusTraversalKeysEnabled, 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, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
JTextArea
public JTextArea()
-
Constructs a new TextArea. A default model is set, the initial string
is null, and rows/columns are set to 0.
JTextArea
public JTextArea(Document doc)
-
Constructs a new JTextArea with the given document model, and defaults
for all of the other arguments (null, 0, 0).
- Parameters:
doc
- the model to use
JTextArea
public JTextArea(Document doc,
String text,
int rows,
int columns)
-
Constructs a new JTextArea with the specified number of rows
and columns, and the given model. All of the constructors
feed through this constructor.
- Parameters:
doc
- the model to use, or create a default one if null
text
- the text to be displayed, null if none
rows
- the number of rows >= 0
columns
- the number of columns >= 0
JTextArea
public JTextArea(int rows,
int columns)
-
Constructs a new empty TextArea with the specified number of
rows and columns. A default model is created, and the initial
string is null.
- Parameters:
rows
- the number of rows >= 0
columns
- the number of columns >= 0
JTextArea
public JTextArea(String text)
-
Constructs a new TextArea with the specified text displayed.
A default model is created and rows/columns are set to 0.
- Parameters:
text
- the text to be displayed, or null
JTextArea
public JTextArea(String text,
int rows,
int columns)
-
Constructs a new TextArea with the specified text and number
of rows and columns. A default model is created.
- Parameters:
text
- the text to be displayed, or null
rows
- the number of rows >= 0
columns
- the number of columns >= 0
append
public void append(String str)
-
Appends the given text to the end of the document. Does nothing if
the model is null or the string is null or empty.
This method is thread safe, although most Swing methods
are not. Please see
How
to Use Threads for more information.
- Parameters:
str
- the text to insert
createDefaultModel
protected Document createDefaultModel()
-
Creates the default implementation of the model
to be used at construction if one isn't explicitly
given. A new instance of PlainDocument is returned.
- Returns:
- the default document model
getAccessibleContext
public AccessibleContext getAccessibleContext()
-
Gets the AccessibleContext associated with this JTextArea.
For JTextAreas, the AccessibleContext takes the form of an
AccessibleJTextArea.
A new AccessibleJTextArea instance is created if necessary.
- Overrides:
getAccessibleContext
in class JTextComponent
- Returns:
- an AccessibleJTextArea that serves as the
AccessibleContext of this JTextArea
getColumns
public int getColumns()
-
Returns the number of columns in the TextArea.
- Returns:
- number of columns >= 0
getColumnWidth
protected int getColumnWidth()
-
Gets column width.
The meaning of what a column is can be considered a fairly weak
notion for some fonts. This method is used to define the width
of a column. By default this is defined to be the width of the
character m for the font used. This method can be
redefined to be some alternative amount.
- Returns:
- the column width >= 1
getLineCount
public int getLineCount()
-
Determines the number of lines contained in the area.
- Returns:
- the number of lines > 0
getLineEndOffset
public int getLineEndOffset(int line)
throws BadLocationException
-
Determines the offset of the end of the given line.
- Parameters:
line
- the line >= 0
- Returns:
- the offset >= 0
- Throws:
BadLocationException
- Thrown if the line is
less than zero or greater or equal to the number of
lines contained in the document (as reported by
getLineCount).
getLineOfOffset
public int getLineOfOffset(int offset)
throws BadLocationException
-
Translates an offset into the components text to a
line number.
- Parameters:
offset
- the offset >= 0
- Returns:
- the line number >= 0
- Throws:
BadLocationException
- thrown if the offset is
less than zero or greater than the document length.
getLineStartOffset
public int getLineStartOffset(int line)
throws BadLocationException
-
Determines the offset of the start of the given line.
- Parameters:
line
- the line number to translate >= 0
- Returns:
- the offset >= 0
- Throws:
BadLocationException
- thrown if the line is
less than zero or greater or equal to the number of
lines contained in the document (as reported by
getLineCount).
getLineWrap
public boolean getLineWrap()
-
Gets the line-wrapping policy of the text area. If set
to true the lines will be wrapped if they are too long
to fit within the allocated width. If set to false,
the lines will always be unwrapped.
- Returns:
- if lines will be wrapped
getPreferredScrollableViewportSize
public Dimension getPreferredScrollableViewportSize()
-
Returns the preferred size of the viewport if this component
is embedded in a JScrollPane. This uses the desired column
and row settings if they have been set, otherwise the superclass
behavior is used.
- Overrides:
getPreferredScrollableViewportSize
in class JTextComponent
- Returns:
- The preferredSize of a JViewport whose view is this Scrollable.
getPreferredSize
public Dimension getPreferredSize()
-
Returns the preferred size of the TextArea. This is the
maximum of the size needed to display the text and the
size requested for the viewport.
- Overrides:
getPreferredSize
in class JComponent
- Returns:
- the size
getRowHeight
protected int getRowHeight()
-
Defines the meaning of the height of a row. This defaults to
the height of the font.
- Returns:
- the height >= 1
getRows
public int getRows()
-
Returns the number of rows in the TextArea.
- Returns:
- the number of rows >= 0
getScrollableTracksViewportWidth
public boolean getScrollableTracksViewportWidth()
-
Returns true if a viewport should always force the width of this
Scrollable to match the width of the viewport. This is implemented
to return true if the line wrapping policy is true, and false
if lines are not being wrapped.
- Overrides:
getScrollableTracksViewportWidth
in class JTextComponent
- Returns:
- true if a viewport should force the Scrollables width
to match its own.
getScrollableUnitIncrement
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)
-
Components that display logical rows or columns should compute
the scroll increment that will completely expose one new row
or column, depending on the value of orientation. This is implemented
to use the values returned by the
getRowHeight
and
getColumnWidth
methods.
Scrolling containers, like JScrollPane, will use this method
each time the user requests a unit scroll.
- Overrides:
getScrollableUnitIncrement
in class JTextComponent
- Parameters:
visibleRect
- the view area visible within the viewport
orientation
- Either SwingConstants.VERTICAL or
SwingConstants.HORIZONTAL.
direction
- Less than zero to scroll up/left,
greater than zero for down/right.
- Returns:
- The "unit" increment for scrolling in the specified direction
getTabSize
public int getTabSize()
-
Gets the number of characters used to expand tabs. If the document is
null or doesn't have a tab setting, return a default of 8.
- Returns:
- the number of characters
getUIClassID
public String getUIClassID()
-
Returns the class ID for the UI.
- Overrides:
getUIClassID
in class JComponent
- Returns:
- the ID ("TextAreaUI")
getWrapStyleWord
public boolean getWrapStyleWord()
-
Gets the style of wrapping used if the text area is wrapping
lines. If set to true the lines will be wrapped at word
boundaries (ie whitespace) if they are too long
to fit within the allocated width. If set to false,
the lines will be wrapped at character boundaries.
- Returns:
- if the wrap style should be word boundaries
instead of character boundaries
insert
public void insert(String str,
int pos)
-
Inserts the specified text at the specified position. Does nothing
if the model is null or if the text is null or empty.
This method is thread safe, although most Swing methods
are not. Please see
How
to Use Threads for more information.
- Parameters:
str
- the text to insert
pos
- the position at which to insert >= 0
paramString
protected String paramString()
-
Returns a string representation of this JTextArea. This method
is intended to be used only for debugging purposes, and the
content and format of the returned string may vary between
implementations. The returned string may be empty but may not
be
null
.
- Overrides:
paramString
in class JTextComponent
- Returns:
- a string representation of this JTextArea.
replaceRange
public void replaceRange(String str,
int start,
int end)
-
Replaces text from the indicated start to end position with the
new text specified. Does nothing if the model is null. Simply
does a delete if the new string is null or empty.
This method is thread safe, although most Swing methods
are not. Please see
How
to Use Threads for more information.
- Parameters:
str
- the text to use as the replacement
start
- the start position >= 0
end
- the end position >= start
setColumns
public void setColumns(int columns)
-
Sets the number of columns for this TextArea. Does an invalidate()
after setting the new value.
- Parameters:
columns
- the number of columns >= 0
setFont
public void setFont(Font f)
-
Sets the current font. This removes cached row height and column
width so the new font will be reflected, and calls revalidate().
- Overrides:
setFont
in class JComponent
- Parameters:
f
- the font to use as the current font
setLineWrap
public void setLineWrap(boolean wrap)
-
Sets the line-wrapping policy of the text area. If set
to true the lines will be wrapped if they are too long
to fit within the allocated width. If set to false,
the lines will always be unwrapped. A
PropertyChange
event ("lineWrap") is fired when the policy is changed.
By default this property is false.
- Parameters:
wrap
- indicates if lines should be wrapped
setRows
public void setRows(int rows)
-
Sets the number of rows for this TextArea. Calls invalidate() after
setting the new value.
- Parameters:
rows
- the number of rows >= 0
setTabSize
public void setTabSize(int size)
-
Sets the number of characters to expand tabs to.
This will be multiplied by the maximum advance for
variable width fonts. A PropertyChange event ("tabSize") is fired
when the tab size changes.
- Parameters:
size
- number of characters to expand to
setWrapStyleWord
public void setWrapStyleWord(boolean word)
-
Sets the style of wrapping used if the text area is wrapping
lines. If set to true the lines will be wrapped at word
boundaries (whitespace) if they are too long
to fit within the allocated width. If set to false,
the lines will be wrapped at character boundaries.
By default this property is false.
- Parameters:
word
- indicates if word boundaries should be used
for line wrapping
This documentation differs from the official API.
Jadeite adds
extra features to the API including:
variable font sizes,
constructions examples,
placeholders for classes and methods, and auto-generated “See Also” links.
Additionally it
is missing some items found in standard Javadoc documentation, including:
generics type information,
“Deprecated” tags and comments,
“See Also” links,
along with other minor differences.
Please send any questions or feedback to
bam@cs.cmu.edu.
This page displays the
Jadeite version of the documention, which is derived from the offical documentation that contains this copyright notice:
The official Sun™ documentation can be found here at
http://java.sun.com/javase/6/docs/api/.