is a multi-line area that displays plain text.
It is intended to be a lightweight component that provides source
compatibility with the
class where it can
reasonably do so.
You can find information and examples of using all the text components in
Constructor: |
public JTextArea() {
this(null, null, 0, 0);
}
Constructs a new TextArea. A default model is set, the initial string
is null, and rows/columns are set to 0. |
public JTextArea(String text) {
this(null, text, 0, 0);
}
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
|
public JTextArea(Document doc) {
this(doc, null, 0, 0);
}
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
|
public JTextArea(int rows,
int columns) {
this(null, null, rows, 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
Throws:
IllegalArgumentException - if the rows or columns
arguments are negative.
- exception:
IllegalArgumentException - if the rows or columns
arguments are negative.
|
public JTextArea(String text,
int rows,
int columns) {
this(null, text, rows, 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
Throws:
IllegalArgumentException - if the rows or columns
arguments are negative.
- exception:
IllegalArgumentException - if the rows or columns
arguments are negative.
|
public JTextArea(Document doc,
String text,
int rows,
int columns) {
super();
this.rows = rows;
this.columns = columns;
if (doc == null) {
doc = createDefaultModel();
}
setDocument(doc);
if (text != null) {
setText(text);
select(0, 0);
}
if (rows < 0) {
throw new IllegalArgumentException("rows: " + rows);
}
if (columns < 0) {
throw new IllegalArgumentException("columns: " + columns);
}
LookAndFeel.installProperty(this,
"focusTraversalKeysForward",
JComponent.
getManagingFocusForwardTraversalKeys());
LookAndFeel.installProperty(this,
"focusTraversalKeysBackward",
JComponent.
getManagingFocusBackwardTraversalKeys());
}
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
Throws:
IllegalArgumentException - if the rows or columns
arguments are negative.
- exception:
IllegalArgumentException - if the rows or columns
arguments are negative.
|
Methods from java.awt.Component: |
---|
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, adjustListeningChildrenOnParent, applyComponentOrientation, applyCompoundShape, applyCurrentShape, areBoundsValid, areFocusTraversalKeysSet, areInputMethodsEnabled, autoProcessMouseWheel, bounds, canBeFocusOwner, canBeFocusOwnerRecursively, checkGD, checkImage, checkImage, checkTreeLock, checkWindowClosingException, clearCurrentFocusCycleRootOnHide, clearMostRecentFocusOwnerOnHide, coalesceEvents, constructComponentName, contains, contains, containsFocus, countHierarchyMembers, createBufferStrategy, createBufferStrategy, createHierarchyEvents, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, disableEvents, dispatchEvent, dispatchEventImpl, dispatchMouseWheelToAncestor, doLayout, enable, enable, enableEvents, enableInputMethods, eventEnabled, eventTypeEnabled, findUnderMouseInWindow, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessControlContext, getAccessibleContext, getAccessibleIndexInParent, getAccessibleStateSet, getAlignmentX, getAlignmentY, getBackBuffer, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getBoundsOp, getBufferStrategy, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getContainer, getContainingWindow, getCursor, getCursor_NoClientCode, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFocusTraversalKeys_NoIDCheck, getFont, getFontMetrics, getFont_NoClientCode, getForeground, getGraphics, getGraphicsConfiguration, getGraphicsConfiguration_NoClientCode, getGraphics_NoClientCode, getHWPeerAboveMe, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getLocationOnScreen_NoTreeLock, getLocationOnWindow, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getNativeContainer, getNextFocusCandidate, getNormalShape, getObjectLock, getOpaqueShape, getParent, getParent_NoClientCode, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSiblingIndexAbove, getSiblingIndexBelow, getSize, getSize, getToolkit, getToolkitImpl, getTraversalRoot, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, initializeFocusTraversalKeys, inside, invalidate, invalidateIfValid, invalidateParent, isAutoFocusTransferOnDisposal, isBackgroundSet, isCoalescingEnabled, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isEnabledImpl, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFocusTraversableOverridden, isFocusable, isFontSet, isForegroundSet, isInstanceOf, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isMixingNeeded, isNonOpaqueForMixing, isOpaque, isPreferredSizeSet, isRecursivelyVisible, isSameOrAncestorOf, isShowing, isValid, isVisible, isVisible_NoClientCode, keyDown, keyUp, layout, lightweightPaint, lightweightPrint, list, list, list, list, list, locate, location, lostFocus, minimumSize, mixOnHiding, mixOnReshaping, mixOnShowing, mixOnValidating, mixOnZOrderChanging, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, numListening, paint, paintAll, paintHeavyweightComponents, paramString, pointRelativeToComponent, postEvent, postsOldMouseEvents, preferredSize, prepareImage, prepareImage, print, printAll, printHeavyweightComponents, processComponentEvent, processEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, relocateComponent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocus, requestFocus, requestFocusHelper, requestFocusHelper, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, revalidate, setAutoFocusTransferOnDisposal, setBackground, setBounds, setBounds, setBoundsOp, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFocusTraversalKeys_NoIDCheck, setFocusable, setFont, setForeground, setGraphicsConfiguration, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setRequestFocusController, setSize, setSize, setVisible, show, show, size, subtractAndApplyShape, subtractAndApplyShapeBelowMe, toString, transferFocus, transferFocus, transferFocusBackward, transferFocusBackward, transferFocusUpCycle, update, updateCursorImmediately, updateGraphicsData, updateZOrder, validate |
Method from javax.swing.JTextArea Detail: |
public void append(String str) {
Document doc = getDocument();
if (doc != null) {
try {
doc.insertString(doc.getLength(), str, null);
} catch (BadLocationException e) {
}
}
}
Appends the given text to the end of the document. Does nothing if
the model is null or the string is null or empty. |
protected Document createDefaultModel() {
return new PlainDocument();
}
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. |
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJTextArea();
}
return accessibleContext;
}
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. |
protected int getColumnWidth() {
if (columnWidth == 0) {
FontMetrics metrics = getFontMetrics(getFont());
columnWidth = metrics.charWidth('m');
}
return columnWidth;
}
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. |
public int getColumns() {
return columns;
}
Returns the number of columns in the TextArea. |
public int getLineCount() {
Element map = getDocument().getDefaultRootElement();
return map.getElementCount();
}
Determines the number of lines contained in the area. |
public int getLineEndOffset(int line) throws BadLocationException {
int lineCount = getLineCount();
if (line < 0) {
throw new BadLocationException("Negative line", -1);
} else if (line >= lineCount) {
throw new BadLocationException("No such line", getDocument().getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
Element lineElem = map.getElement(line);
int endOffset = lineElem.getEndOffset();
// hide the implicit break at the end of the document
return ((line == lineCount - 1) ? (endOffset - 1) : endOffset);
}
}
Determines the offset of the end of the given line. |
public int getLineOfOffset(int offset) throws BadLocationException {
Document doc = getDocument();
if (offset < 0) {
throw new BadLocationException("Can't translate offset to line", -1);
} else if (offset > doc.getLength()) {
throw new BadLocationException("Can't translate offset to line", doc.getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
return map.getElementIndex(offset);
}
}
Translates an offset into the components text to a
line number. |
public int getLineStartOffset(int line) throws BadLocationException {
int lineCount = getLineCount();
if (line < 0) {
throw new BadLocationException("Negative line", -1);
} else if (line >= lineCount) {
throw new BadLocationException("No such line", getDocument().getLength()+1);
} else {
Element map = getDocument().getDefaultRootElement();
Element lineElem = map.getElement(line);
return lineElem.getStartOffset();
}
}
Determines the offset of the start of the given line. |
public boolean getLineWrap() {
return wrap;
}
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. |
public Dimension getPreferredScrollableViewportSize() {
Dimension size = super.getPreferredScrollableViewportSize();
size = (size == null) ? new Dimension(400,400) : size;
Insets insets = getInsets();
size.width = (columns == 0) ? size.width :
columns * getColumnWidth() + insets.left + insets.right;
size.height = (rows == 0) ? size.height :
rows * getRowHeight() + insets.top + insets.bottom;
return size;
}
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. |
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
d = (d == null) ? new Dimension(400,400) : d;
Insets insets = getInsets();
if (columns != 0) {
d.width = Math.max(d.width, columns * getColumnWidth() +
insets.left + insets.right);
}
if (rows != 0) {
d.height = Math.max(d.height, rows * getRowHeight() +
insets.top + insets.bottom);
}
return d;
}
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. |
protected int getRowHeight() {
if (rowHeight == 0) {
FontMetrics metrics = getFontMetrics(getFont());
rowHeight = metrics.getHeight();
}
return rowHeight;
}
Defines the meaning of the height of a row. This defaults to
the height of the font. |
public int getRows() {
return rows;
}
Returns the number of rows in the TextArea. |
public boolean getScrollableTracksViewportWidth() {
return (wrap) ? true : super.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. |
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction) {
switch (orientation) {
case SwingConstants.VERTICAL:
return getRowHeight();
case SwingConstants.HORIZONTAL:
return getColumnWidth();
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
}
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. |
public int getTabSize() {
int size = 8;
Document doc = getDocument();
if (doc != null) {
Integer i = (Integer) doc.getProperty(PlainDocument.tabSizeAttribute);
if (i != null) {
size = i.intValue();
}
}
return size;
}
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. |
public String getUIClassID() {
return uiClassID;
}
Returns the class ID for the UI. |
public boolean getWrapStyleWord() {
return word;
}
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. |
public void insert(String str,
int pos) {
Document doc = getDocument();
if (doc != null) {
try {
doc.insertString(pos, str, null);
} catch (BadLocationException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
Inserts the specified text at the specified position. Does nothing
if the model is null or if the text is null or empty. |
protected String paramString() {
String wrapString = (wrap ?
"true" : "false");
String wordString = (word ?
"true" : "false");
return super.paramString() +
",colums=" + columns +
",columWidth=" + columnWidth +
",rows=" + rows +
",rowHeight=" + rowHeight +
",word=" + wordString +
",wrap=" + wrapString;
}
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 . |
public void replaceRange(String str,
int start,
int end) {
if (end < start) {
throw new IllegalArgumentException("end before start");
}
Document doc = getDocument();
if (doc != null) {
try {
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(start, end - start, str,
null);
}
else {
doc.remove(start, end - start);
doc.insertString(start, str, null);
}
} catch (BadLocationException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
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. |
public void setColumns(int columns) {
int oldVal = this.columns;
if (columns < 0) {
throw new IllegalArgumentException("columns less than zero.");
}
if (columns != oldVal) {
this.columns = columns;
invalidate();
}
}
Sets the number of columns for this TextArea. Does an invalidate()
after setting the new value. |
public void setFont(Font f) {
super.setFont(f);
rowHeight = 0;
columnWidth = 0;
}
Sets the current font. This removes cached row height and column
width so the new font will be reflected, and calls revalidate(). |
public void setLineWrap(boolean wrap) {
boolean old = this.wrap;
this.wrap = wrap;
firePropertyChange("lineWrap", old, 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. |
public void setRows(int rows) {
int oldVal = this.rows;
if (rows < 0) {
throw new IllegalArgumentException("rows less than zero.");
}
if (rows != oldVal) {
this.rows = rows;
invalidate();
}
}
Sets the number of rows for this TextArea. Calls invalidate() after
setting the new value. |
public void setTabSize(int size) {
Document doc = getDocument();
if (doc != null) {
int old = getTabSize();
doc.putProperty(PlainDocument.tabSizeAttribute, Integer.valueOf(size));
firePropertyChange("tabSize", old, 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. |
public void setWrapStyleWord(boolean word) {
boolean old = this.word;
this.word = word;
firePropertyChange("wrapStyleWord", old, 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. |