Top Description Inners Fields Constructors Methods
javax.swing

public Class JTextArea

extends JTextComponent
Class Inheritance
Known Direct Subclasses
sun.awt.X11.XTextAreaPeer.AWTTextArea
Annotations
@JavaBean
defaultProperty:UIClassID
description:A multi-line area that displays plain text.
@SwingContainer:false
@SuppressWarnings:serial
Imports
java.awt.Dimension, .Font, .FontMetrics, .Insets, .Rectangle, .TextComponent, java.beans.BeanProperty, .JavaBean, java.io.IOException, .ObjectOutputStream, .Serial, javax.accessibility.AccessibleContext, .AccessibleState, .AccessibleStateSet, javax.swing.text.AbstractDocument, .BadLocationException, .Document, .Element, .JTextComponent, .PlainDocument

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 TextEvents. 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 JavaBeans has been added to the java.beans package. Please see java.beans.XMLEncoder.

Author
Timothy Prinzing
Since
1.2
See Also
JTextPane, JEditorPane

Nested and Inner Type Summary

Modifier and TypeClass and Description
protected class
JTextArea.AccessibleJTextArea

This class implements accessibility support for the JTextArea class.

Field Summary

Modifier and TypeField and Description
private int
private int
private int
private int
private static final String
private boolean
private boolean
Inherited from javax.swing.text.JTextComponent:
DEFAULT_KEYMAPFOCUS_ACCELERATOR_KEY

Constructor Summary

AccessConstructor and Description
public
JTextArea()

Constructs a new TextArea.

public
JTextArea(String
the text to be displayed, or null
text
)

Constructs a new TextArea with the specified text displayed.

public
JTextArea(int
the number of rows >= 0
rows
,
int
the number of columns >= 0
columns
)

Constructs a new empty TextArea with the specified number of rows and columns.

public
JTextArea(String
the text to be displayed, or null
text
,
int
the number of rows >= 0
rows
,
int
the number of columns >= 0
columns
)

Constructs a new TextArea with the specified text and number of rows and columns.

public
JTextArea(Document
the model to use
doc
)

Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0).

public
JTextArea(Document
the model to use, or create a default one if null
doc
,
String
the text to be displayed, null if none
text
,
int
the number of rows >= 0
rows
,
int
the number of columns >= 0
columns
)

Constructs a new JTextArea with the specified number of rows and columns, and the given model.

Method Summary

Modifier and TypeMethod and Description
public void
append(String
the text to insert
str
)

Appends the given text to the end of the document.

protected Document

Returns:

the default document model
createDefaultModel
()

Creates the default implementation of the model to be used at construction if one isn't explicitly given.

public AccessibleContext

Returns:

an AccessibleJTextArea that serves as the AccessibleContext of this JTextArea
getAccessibleContext
()

Overrides javax.swing.text.JTextComponent.getAccessibleContext.

Implements javax.accessibility.Accessible.getAccessibleContext.

Gets the AccessibleContext associated with this JTextArea.
public int

Returns:

number of columns >= 0
getColumns
()

Returns the number of columns in the TextArea.

protected int

Returns:

the column width >= 1
getColumnWidth
()

Gets column width.

public int

Returns:

the number of lines > 0
getLineCount
()

Determines the number of lines contained in the area.

public int

Returns:

the offset >= 0
getLineEndOffset
(int
the line >= 0
line
)

Determines the offset of the end of the given line.

public int

Returns:

the line number >= 0
getLineOfOffset
(int
the offset >= 0
offset
)

Translates an offset into the components text to a line number.

public int

Returns:

the offset >= 0
getLineStartOffset
(int
the line number to translate >= 0
line
)

Determines the offset of the start of the given line.

public boolean

Returns:

if lines will be wrapped
getLineWrap
()

Gets the line-wrapping policy of the text area.

public Dimension

Returns:

The preferredSize of a JViewport whose view is this Scrollable.
getPreferredScrollableViewportSize
()

Overrides javax.swing.text.JTextComponent.getPreferredScrollableViewportSize.

Implements javax.swing.Scrollable.getPreferredScrollableViewportSize.

Returns the preferred size of the viewport if this component is embedded in a JScrollPane.
public Dimension

Returns:

the size
getPreferredSize
()

Overrides javax.swing.JComponent.getPreferredSize.

Returns the preferred size of the TextArea.
protected int

Returns:

the height >= 1
getRowHeight
()

Defines the meaning of the height of a row.

public int

Returns:

the number of rows >= 0
getRows
()

Returns the number of rows in the TextArea.

public boolean

Returns:

true if a viewport should force the Scrollables width to match its own.
getScrollableTracksViewportWidth
()

Overrides javax.swing.text.JTextComponent.getScrollableTracksViewportWidth.

Implements javax.swing.Scrollable.getScrollableTracksViewportWidth.

Returns true if a viewport should always force the width of this Scrollable to match the width of the viewport.
public int

Returns:

The "unit" increment for scrolling in the specified direction
getScrollableUnitIncrement
(Rectangle
the view area visible within the viewport
visibleRect
,
int
Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
orientation
,
int
Less than zero to scroll up/left, greater than zero for down/right.
direction
)

Overrides javax.swing.text.JTextComponent.getScrollableUnitIncrement.

Implements javax.swing.Scrollable.getScrollableUnitIncrement.

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.
public int

Returns:

the number of characters
getTabSize
()

Gets the number of characters used to expand tabs.

public String

Returns:

the string "TextAreaUI"
getUIClassID
()

Overrides javax.swing.JComponent.getUIClassID.

Returns the class ID for the UI.
public boolean

Returns:

if the wrap style should be word boundaries instead of character boundaries
getWrapStyleWord
()

Gets the style of wrapping used if the text area is wrapping lines.

public void
insert(String
the text to insert
str
,
int
the position at which to insert >= 0
pos
)

Inserts the specified text at the specified position.

protected String

Returns:

a string representation of this JTextArea.
paramString
()

Overrides javax.swing.text.JTextComponent.paramString.

Returns a string representation of this JTextArea.
public void
replaceRange(String
the text to use as the replacement
str
,
int
the start position >= 0
start
,
int
the end position >= start
end
)

Replaces text from the indicated start to end position with the new text specified.

public void
setColumns(int
the number of columns >= 0
columns
)

Sets the number of columns for this TextArea.

public void
setFont(Font
the font to use as the current font
f
)

Overrides javax.swing.JComponent.setFont.

Sets the current font.
public void
setLineWrap(boolean
indicates if lines should be wrapped
wrap
)

Sets the line-wrapping policy of the text area.

public void
setRows(int
the number of rows >= 0
rows
)

Sets the number of rows for this TextArea.

public void
setTabSize(int
number of characters to expand to
size
)

Sets the number of characters to expand tabs to.

public void
setWrapStyleWord(boolean
indicates if word boundaries should be used for line wrapping
word
)

Sets the style of wrapping used if the text area is wrapping lines.

private void
writeObject(ObjectOutputStream
the ObjectOutputStream in which to write
s
)

Hides javax.swing.JComponent.writeObject.

See readObject() and writeObject() in JComponent for more information about serialization in Swing.
Inherited from javax.swing.text.JTextComponent:
addCaretListeneraddInputMethodListeneraddKeymapcopycutfireCaretUpdategetActionsgetCaretgetCaretColorgetCaretListenersgetCaretPositiongetDisabledTextColorgetDocumentgetDragEnabledgetDropLocationgetDropModegetFocusAcceleratorgetHighlightergetInputMethodRequestsgetKeymapgetKeymapgetMargingetNavigationFiltergetPrintablegetScrollableBlockIncrementgetScrollableTracksViewportHeightgetSelectedTextgetSelectedTextColorgetSelectionColorgetSelectionEndgetSelectionStartgetTextgetTextgetToolTipTextgetUIisEditableloadKeymapmodelToViewmodelToView2DmoveCaretPositionpasteprintprintprintprocessInputMethodEventreadremoveCaretListenerremoveKeymapremoveNotifyreplaceSelectionrestoreComposedTextsaveComposedTextselectselectAllsetCaretsetCaretColorsetCaretPositionsetComponentOrientationsetDisabledTextColorsetDocumentsetDragEnabledsetDropModesetEditablesetFocusAcceleratorsetHighlightersetKeymapsetMarginsetNavigationFiltersetSelectedTextColorsetSelectionColorsetSelectionEndsetSelectionStartsetTextsetUIupdateUIviewToModelviewToModel2Dwrite

Field Detail

columnsback to summary
private int columns
columnWidthback to summary
private int columnWidth
rowHeightback to summary
private int rowHeight
rowsback to summary
private int rows
uiClassIDback to summary
private static final String uiClassID

Hides javax.swing.JComponent.uiClassID.

See Also
getUIClassID, readObject
wordback to summary
private boolean word
wrapback to summary
private boolean wrap

Constructor Detail

JTextAreaback to summary
public JTextArea()

Constructs a new TextArea. A default model is set, the initial string is null, and rows/columns are set to 0.

JTextAreaback to summary
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:String

the text to be displayed, or null

JTextAreaback to summary
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:int

the number of rows >= 0

columns:int

the number of columns >= 0

Exceptions
IllegalArgumentException:
if the rows or columns arguments are negative.
JTextAreaback to summary
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:String

the text to be displayed, or null

rows:int

the number of rows >= 0

columns:int

the number of columns >= 0

Exceptions
IllegalArgumentException:
if the rows or columns arguments are negative.
JTextAreaback to summary
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:Document

the model to use

JTextAreaback to summary
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:Document

the model to use, or create a default one if null

text:String

the text to be displayed, null if none

rows:int

the number of rows >= 0

columns:int

the number of columns >= 0

Exceptions
IllegalArgumentException:
if the rows or columns arguments are negative.

Method Detail

appendback to summary
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.

Parameters
str:String

the text to insert

See Also
insert
createDefaultModelback to summary
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:Document

the default document model

getAccessibleContextback to summary
public AccessibleContext getAccessibleContext()

Overrides javax.swing.text.JTextComponent.getAccessibleContext.

Implements javax.accessibility.Accessible.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.

Returns:AccessibleContext

an AccessibleJTextArea that serves as the AccessibleContext of this JTextArea

Annotations
@BeanProperty
bound:false
getColumnsback to summary
public int getColumns()

Returns the number of columns in the TextArea.

Returns:int

number of columns >= 0

getColumnWidthback to summary
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:int

the column width >= 1

getLineCountback to summary
public int getLineCount()

Determines the number of lines contained in the area.

Returns:int

the number of lines > 0

Annotations
@BeanProperty
bound:false
getLineEndOffsetback to summary
public int getLineEndOffset(int line) throws BadLocationException

Determines the offset of the end of the given line.

Parameters
line:int

the line >= 0

Returns:int

the offset >= 0

Exceptions
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).
getLineOfOffsetback to summary
public int getLineOfOffset(int offset) throws BadLocationException

Translates an offset into the components text to a line number.

Parameters
offset:int

the offset >= 0

Returns:int

the line number >= 0

Exceptions
BadLocationException:
thrown if the offset is less than zero or greater than the document length.
getLineStartOffsetback to summary
public int getLineStartOffset(int line) throws BadLocationException

Determines the offset of the start of the given line.

Parameters
line:int

the line number to translate >= 0

Returns:int

the offset >= 0

Exceptions
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).
getLineWrapback to summary
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:boolean

if lines will be wrapped

getPreferredScrollableViewportSizeback to summary
public Dimension getPreferredScrollableViewportSize()

Overrides javax.swing.text.JTextComponent.getPreferredScrollableViewportSize.

Implements javax.swing.Scrollable.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.

Returns:Dimension

The preferredSize of a JViewport whose view is this Scrollable.

Annotations
@BeanProperty
bound:false
See Also
JViewport#getPreferredSize
getPreferredSizeback to summary
public Dimension getPreferredSize()

Overrides javax.swing.JComponent.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.

Returns:Dimension

the size

getRowHeightback to summary
protected int getRowHeight()

Defines the meaning of the height of a row. This defaults to the height of the font.

Returns:int

the height >= 1

getRowsback to summary
public int getRows()

Returns the number of rows in the TextArea.

Returns:int

the number of rows >= 0

getScrollableTracksViewportWidthback to summary
public boolean getScrollableTracksViewportWidth()

Overrides javax.swing.text.JTextComponent.getScrollableTracksViewportWidth.

Implements javax.swing.Scrollable.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.

Returns:boolean

true if a viewport should force the Scrollables width to match its own.

Annotations
@BeanProperty
bound:false
getScrollableUnitIncrementback to summary
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

Overrides javax.swing.text.JTextComponent.getScrollableUnitIncrement.

Implements javax.swing.Scrollable.getScrollableUnitIncrement.

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.

Parameters
visibleRect:Rectangle

the view area visible within the viewport

orientation:int

Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.

direction:int

Less than zero to scroll up/left, greater than zero for down/right.

Returns:int

The "unit" increment for scrolling in the specified direction

Exceptions
IllegalArgumentException:
for an invalid orientation
See Also
JScrollBar#setUnitIncrement, getRowHeight, getColumnWidth
getTabSizeback to summary
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:int

the number of characters

getUIClassIDback to summary
public String getUIClassID()

Overrides javax.swing.JComponent.getUIClassID.

Returns the class ID for the UI.

Returns:String

the string "TextAreaUI"

Annotations
@BeanProperty
bound:false
See Also
JComponent#getUIClassID, UIDefaults#getUI
getWrapStyleWordback to summary
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:boolean

if the wrap style should be word boundaries instead of character boundaries

See Also
setWrapStyleWord
insertback to summary
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.

Parameters
str:String

the text to insert

pos:int

the position at which to insert >= 0

Exceptions
IllegalArgumentException:
if pos is an invalid position in the model
See Also
TextComponent#setText, replaceRange
paramStringback to summary
protected String paramString()

Overrides javax.swing.text.JTextComponent.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.

Returns:String

a string representation of this JTextArea.

replaceRangeback to summary
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.

Parameters
str:String

the text to use as the replacement

start:int

the start position >= 0

end:int

the end position >= start

Exceptions
IllegalArgumentException:
if part of the range is an invalid position in the model
See Also
insert
setColumnsback to summary
public void setColumns(int columns)

Sets the number of columns for this TextArea. Does an invalidate() after setting the new value.

Parameters
columns:int

the number of columns >= 0

Annotations
@BeanProperty
bound:false
description:the number of columns preferred for display
Exceptions
IllegalArgumentException:
if columns is less than 0
See Also
getColumns
setFontback to summary
public void setFont(Font f)

Overrides javax.swing.JComponent.setFont.

Sets the current font. This removes cached row height and column width so the new font will be reflected, and calls revalidate().

Parameters
f:Font

the font to use as the current font

setLineWrapback to summary
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:boolean

indicates if lines should be wrapped

Annotations
@BeanProperty
preferred:true
description:should lines be wrapped
See Also
getLineWrap
setRowsback to summary
public void setRows(int rows)

Sets the number of rows for this TextArea. Calls invalidate() after setting the new value.

Parameters
rows:int

the number of rows >= 0

Annotations
@BeanProperty
bound:false
description:the number of rows preferred for display
Exceptions
IllegalArgumentException:
if rows is less than 0
See Also
getRows
setTabSizeback to summary
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:int

number of characters to expand to

Annotations
@BeanProperty
preferred:true
description:the number of characters to expand tabs to
See Also
getTabSize
setWrapStyleWordback to summary
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:boolean

indicates if word boundaries should be used for line wrapping

Annotations
@BeanProperty
description:should wrapping occur at word boundaries
See Also
getWrapStyleWord
writeObjectback to summary
private void writeObject(ObjectOutputStream s) throws IOException

Hides javax.swing.JComponent.writeObject.

See readObject() and writeObject() in JComponent for more information about serialization in Swing.

Parameters
s:ObjectOutputStream

Doc from javax.swing.JComponent.writeObject.

the ObjectOutputStream in which to write

Annotations
@Serial
Exceptions
IOException:

Doc from java.awt.Container.writeObject.

if an I/O error occurs

javax.swing back to summary

protected Class JTextArea.AccessibleJTextArea

extends AccessibleJTextComponent
Class Inheritance
Annotations
@SuppressWarnings:serial

This class implements accessibility support for the JTextArea class. It provides an implementation of the Java Accessibility API appropriate to text area user-interface elements.

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 JavaBeans has been added to the java.beans package. Please see java.beans.XMLEncoder.

Constructor Summary

AccessConstructor and Description
protected
AccessibleJTextArea()

Constructs an AccessibleJTextArea.

Method Summary

Modifier and TypeMethod and Description
public AccessibleStateSet

Returns:

an instance of AccessibleStateSet describing the states of the object
getAccessibleStateSet
()

Overrides javax.swing.text.JTextComponent.AccessibleJTextComponent.getAccessibleStateSet.

Gets the state set of this object.
Inherited from javax.swing.text.JTextComponent.AccessibleJTextComponent:
caretUpdatechangedUpdatecutdeletedoAccessibleActiongetAccessibleActiongetAccessibleActionCountgetAccessibleActionDescriptiongetAccessibleEditableTextgetAccessibleRolegetAccessibleTextgetAfterIndexgetAtIndexgetBeforeIndexgetCaretPositiongetCharacterAttributegetCharacterBoundsgetCharCountgetIndexAtPointgetSelectedTextgetSelectionEndgetSelectionStartgetTextBoundsgetTextRangegetTextSequenceAftergetTextSequenceAtgetTextSequenceBeforeinsertTextAtIndexinsertUpdatepasteremoveUpdatereplaceTextselectTextsetAttributessetTextContents

Constructor Detail

AccessibleJTextAreaback to summary
protected AccessibleJTextArea()

Constructs an AccessibleJTextArea.

Method Detail

getAccessibleStateSetback to summary
public AccessibleStateSet getAccessibleStateSet()

Overrides javax.swing.text.JTextComponent.AccessibleJTextComponent.getAccessibleStateSet.

Gets the state set of this object.

Returns:AccessibleStateSet

an instance of AccessibleStateSet describing the states of the object

See Also
AccessibleStateSet