ImageObserver
, MenuContainer
, Serializable
, Accessible
, Scrollable
@JavaBean(defaultProperty="UIClassID", description="A multi-line area that displays plain text.") public class JTextArea extends JTextComponent
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);
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 XMLEncoder
.
Modifier and Type | Class | Description |
---|---|---|
protected class |
JTextArea.AccessibleJTextArea |
This class implements accessibility support for the JTextArea class. |
JTextComponent.AccessibleJTextComponent, JTextComponent.DropLocation, JTextComponent.KeyBinding
JComponent.AccessibleJComponent
Container.AccessibleAWTContainer
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
DEFAULT_KEYMAP, FOCUS_ACCELERATOR_KEY
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
Constructor | Description |
---|---|
JTextArea() |
Constructs a new TextArea. |
JTextArea |
Constructs a new empty TextArea with the specified number of rows and columns. |
JTextArea |
Constructs a new TextArea with the specified text displayed. |
JTextArea |
Constructs a new TextArea with the specified text and number of rows and columns. |
JTextArea |
Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0). |
JTextArea |
Constructs a new JTextArea with the specified number of rows and columns, and the given model. |
Modifier and Type | Method | Description |
---|---|---|
void |
append |
Appends the given text to the end of the document. |
protected Document |
createDefaultModel() |
Creates the default implementation of the model to be used at construction if one isn't explicitly given. |
AccessibleContext |
getAccessibleContext() |
Gets the AccessibleContext associated with this JTextArea. |
int |
getColumns() |
Returns the number of columns in the TextArea. |
protected int |
getColumnWidth() |
Gets column width. |
int |
getLineCount() |
Determines the number of lines contained in the area. |
int |
getLineEndOffset |
Determines the offset of the end of the given line. |
int |
getLineOfOffset |
Translates an offset into the components text to a line number. |
int |
getLineStartOffset |
Determines the offset of the start of the given line. |
boolean |
getLineWrap() |
Gets the line-wrapping policy of the text area. |
Dimension |
getPreferredScrollableViewportSize() |
Returns the preferred size of the viewport if this component is embedded in a JScrollPane. |
Dimension |
getPreferredSize() |
Returns the preferred size of the TextArea. |
protected int |
getRowHeight() |
Defines the meaning of the height of a row. |
int |
getRows() |
Returns the number of rows in the TextArea. |
boolean |
getScrollableTracksViewportWidth() |
Returns true if a viewport should always force the width of this Scrollable to match the width of the viewport. |
int |
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. |
int |
getTabSize() |
Gets the number of characters used to expand tabs. |
String |
getUIClassID() |
Returns the class ID for the UI. |
boolean |
getWrapStyleWord() |
Gets the style of wrapping used if the text area is wrapping lines. |
void |
insert |
Inserts the specified text at the specified position. |
protected String |
paramString() |
Returns a string representation of this JTextArea. |
void |
replaceRange |
Replaces text from the indicated start to end position with the new text specified. |
void |
setColumns |
Sets the number of columns for this TextArea. |
void |
setFont |
Sets the current font. |
void |
setLineWrap |
Sets the line-wrapping policy of the text area. |
void |
setRows |
Sets the number of rows for this TextArea. |
void |
setTabSize |
Sets the number of characters to expand tabs to. |
void |
setWrapStyleWord |
Sets the style of wrapping used if the text area is wrapping lines. |
addCaretListener, addKeymap, copy, cut, fireCaretUpdate, getActions, getCaret, getCaretColor, getCaretListeners, getCaretPosition, getDisabledTextColor, getDocument, getDragEnabled, getDropLocation, getDropMode, getFocusAccelerator, getHighlighter, getInputMethodRequests, getKeymap, getKeymap, getMargin, getNavigationFilter, getPrintable, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getSelectedText, getSelectedTextColor, getSelectionColor, getSelectionEnd, getSelectionStart, getText, getText, getToolTipText, getUI, isEditable, loadKeymap, modelToView, modelToView2D, moveCaretPosition, paste, print, print, print, read, removeCaretListener, removeKeymap, replaceSelection, restoreComposedText, saveComposedText, select, selectAll, setCaret, setCaretColor, setCaretPosition, setDisabledTextColor, setDocument, setDragEnabled, setDropMode, setEditable, setFocusAccelerator, setHighlighter, setKeymap, setMargin, setNavigationFilter, setSelectedTextColor, setSelectionColor, setSelectionEnd, setSelectionStart, setText, setUI, updateUI, viewToModel, viewToModel2D, write
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, fireVetoableChange, 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, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, 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, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
public JTextArea()
public JTextArea(String text)
text
- the text to be displayed, or nullpublic JTextArea(int rows, int columns)
rows
- the number of rows >= 0columns
- the number of columns >= 0IllegalArgumentException
- if the rows or columns arguments are negative.public JTextArea(String text, int rows, int columns)
text
- the text to be displayed, or nullrows
- the number of rows >= 0columns
- the number of columns >= 0IllegalArgumentException
- if the rows or columns arguments are negative.public JTextArea(Document doc)
doc
- the model to usepublic JTextArea(Document doc, String text, int rows, int columns)
doc
- the model to use, or create a default one if nulltext
- the text to be displayed, null if nonerows
- the number of rows >= 0columns
- the number of columns >= 0IllegalArgumentException
- if the rows or columns arguments are negative.@BeanProperty(bound=false) public String getUIClassID()
getUIClassID
in class JComponent
protected Document createDefaultModel()
@BeanProperty(preferred=true, description="the number of characters to expand tabs to") public void setTabSize(int size)
size
- number of characters to expand topublic int getTabSize()
@BeanProperty(preferred=true, description="should lines be wrapped") public void setLineWrap(boolean wrap)
PropertyChange
event ("lineWrap") is fired when the policy is changed. By default this property is false.wrap
- indicates if lines should be wrappedpublic boolean getLineWrap()
@BeanProperty(description="should wrapping occur at word boundaries") public void setWrapStyleWord(boolean word)
word
- indicates if word boundaries should be used for line wrappingpublic boolean getWrapStyleWord()
public int getLineOfOffset(int offset) throws BadLocationException
offset
- the offset >= 0BadLocationException
- thrown if the offset is less than zero or greater than the document length.@BeanProperty(bound=false) public int getLineCount()
public int getLineStartOffset(int line) throws BadLocationException
line
- the line number to translate >= 0BadLocationException
- 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).public int getLineEndOffset(int line) throws BadLocationException
line
- the line >= 0BadLocationException
- 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).public void insert(String str, int pos)
str
- the text to insertpos
- the position at which to insert >= 0IllegalArgumentException
- if pos is an invalid position in the modelpublic void append(String str)
str
- the text to insertpublic void replaceRange(String str, int start, int end)
str
- the text to use as the replacementstart
- the start position >= 0end
- the end position >= startIllegalArgumentException
- if part of the range is an invalid position in the modelpublic int getRows()
@BeanProperty(bound=false, description="the number of rows preferred for display") public void setRows(int rows)
rows
- the number of rows >= 0IllegalArgumentException
- if rows is less than 0protected int getRowHeight()
public int getColumns()
@BeanProperty(bound=false, description="the number of columns preferred for display") public void setColumns(int columns)
columns
- the number of columns >= 0IllegalArgumentException
- if columns is less than 0protected int getColumnWidth()
public Dimension getPreferredSize()
getPreferredSize
in class JComponent
public void setFont(Font f)
setFont
in class JComponent
f
- the font to use as the current fontprotected String paramString()
null
.paramString
in class JTextComponent
@BeanProperty(bound=false) public boolean getScrollableTracksViewportWidth()
getScrollableTracksViewportWidth
in interface Scrollable
getScrollableTracksViewportWidth
in class JTextComponent
@BeanProperty(bound=false) public Dimension getPreferredScrollableViewportSize()
getPreferredScrollableViewportSize
in interface Scrollable
getPreferredScrollableViewportSize
in class JTextComponent
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
getRowHeight
and getColumnWidth
methods. Scrolling containers, like JScrollPane, will use this method each time the user requests a unit scroll.
getScrollableUnitIncrement
in interface Scrollable
getScrollableUnitIncrement
in class JTextComponent
visibleRect
- the view area visible within the viewportorientation
- Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.direction
- Less than zero to scroll up/left, greater than zero for down/right.IllegalArgumentException
- for an invalid orientation@BeanProperty(bound=false) public AccessibleContext getAccessibleContext()
getAccessibleContext
in interface Accessible
getAccessibleContext
in class JTextComponent
© 1993, 2023, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/JTextArea.html