Safe:JTextComponent is the base class for swing text
components. It tries to be compatible with the
java.awt.TextComponent class
where it can reasonably do so. Also provided are other services
for additional flexibility (beyond the pluggable UI and bean
support).
You can find information on how to use the functionality
this class provides in
General Rules for Using Text Components,
a section in The Java Tutorial.

Caret Changes

The caret is a pluggable object in swing text components.
Notification of changes to the caret position and the selection
are sent to implementations of the CaretListener
interface that have been registered with the text component.
The UI will install a default caret unless a customized caret
has been set.

Commands

Text components provide a number of commands that can be used
to manipulate the component. This is essentially the way that
the component expresses its capabilities. These are expressed
in terms of the swing Action interface,
using the TextAction implementation.
The set of commands supported by the text component can be
found with the getActions() method. These actions
can be bound to key events, fired from buttons, etc.

Text Input

The text components support flexible and internationalized text input, using
keymaps and the input method framework, while maintaining compatibility with
the AWT listener model.

A javax.swing.text.Keymap lets an application bind key
strokes to actions.
In order to allow keymaps to be shared across multiple text components, they
can use actions that extend TextAction.
TextAction can determine which JTextComponent
most recently has or had focus and therefore is the subject of
the action (In the case that the ActionEvent
sent to the action doesn't contain the target text component as its source).

The input method framework
lets text components interact with input methods, separate software
components that preprocess events to let users enter thousands of
different characters using keyboards with far fewer keys.
JTextComponent is an active client of
the framework, so it implements the preferred user interface for interacting
with input methods. As a consequence, some key events do not reach the text
component because they are handled by an input method, and some text input
reaches the text component as committed text within an java.awt.event.InputMethodEvent instead of as a key event.
The complete text input is the combination of the characters in
keyTyped key events and committed text in input method events.

The AWT listener model lets applications attach event listeners to
components in order to bind events to actions. Swing encourages the
use of keymaps instead of listeners, but maintains compatibility
with listeners by giving the listeners a chance to steal an event
by consuming it.

Keyboard event and input method events are handled in the following stages,
with each stage capable of consuming the event:

To maintain compatibility with applications that listen to key
events but are not aware of input method events, the input
method handling in stage 4 provides a compatibility mode for
components that do not process input method events. For these
components, the committed text is converted to keyTyped key events
and processed in the key event pipeline starting at stage 3
instead of in the input method event pipeline.

By default the component will create a keymap (named DEFAULT_KEYMAP)
that is shared by all JTextComponent instances as the default keymap.
Typically a look-and-feel implementation will install a different keymap
that resolves to the default keymap for those bindings not found in the
different keymap. The minimal bindings include:

inserting content into the editor for the
printable keys.

removing content with the backspace and del
keys.

caret movement forward and backward

Model/View Split

The text components have a model-view split. A text component pulls
together the objects used to represent the model, view, and controller.
The text document model may be shared by other views which act as observers
of the model (e.g. a document may be shared by multiple components).

The model is defined by the Document interface.
This is intended to provide a flexible text storage mechanism
that tracks change during edits and can be extended to more sophisticated
models. The model interfaces are meant to capture the capabilities of
expression given by SGML, a system used to express a wide variety of
content.
Each modification to the document causes notification of the
details of the change to be sent to all observers in the form of a
DocumentEvent which allows the views to stay up to date with the model.
This event is sent to observers that have implemented the
DocumentListener
interface and registered interest with the model being observed.

Support for an edit history mechanism is provided to allow
undo/redo operations. The text component does not itself
provide the history buffer by default, but does provide
the UndoableEdit records that can be used in conjunction
with a history buffer to provide the undo/redo support.
The support is provided by the Document model, which allows
one to attach UndoableEditListener implementations.

Thread Safety

The swing text components provide some support of thread
safe operations. Because of the high level of configurability
of the text components, it is possible to circumvent the
protection provided. The protection primarily comes from
the model, so the documentation of AbstractDocument
describes the assumptions of the protection provided.
The methods that are safe to call asynchronously are marked
with comments.

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 java.beans.XMLEncoder.

getScrollableBlockIncrement(Rectangle visibleRect,
int orientation,
int direction)Enabled: Components that display logical rows or columns should compute
the scroll increment that will completely expose one block
of rows or columns, depending on the value of orientation.

getScrollableUnitIncrement(Rectangle visibleRect,
int orientation,
int direction)Enabled: 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.

needToSendKeyTypedEvent

DEFAULT_KEYMAP

Suppressed: The default keymap that will be shared by all
JTextComponent instances unless they
have had a different keymap set.

Constructor Detail

JTextComponent

public JTextComponent()

Enabled: Creates a new JTextComponent.
Listeners for caret events are established, and the pluggable
UI installed. The component is marked as editable. No layout manager
is used, because layout is managed by the view subsystem of text.
The document model is set to null.

Method Detail

getUI

public javax.swing.plaf.TextUI getUI()

Suppressed: Fetches the user-interface factory for this text-oriented editor.

Returns:

the factory

setUI

public void setUI(javax.swing.plaf.TextUI ui)

Suppressed: Sets the user-interface factory for this text-oriented editor.

Parameters:

ui - the factory

updateUI

public void updateUI()

Suppressed: Reloads the pluggable UI. The key used to fetch the
new interface is getUIClassID(). The type of
the UI is TextUI. invalidate
is called after setting the UI.

fireCaretUpdate

Notifies all listeners that have registered interest for
notification on this event type. The event instance
is lazily created using the parameters passed into
the fire method. The listener list is processed in a
last-to-first manner.

setDocument

Enabled: Associates the editor with a text document.
The currently registered factory is used to build a view for
the document, which gets displayed by the editor after revalidation.
A PropertyChange event ("document") is propagated to each listener.

getDocument

Enabled: Fetches the model associated with the editor. This is
primarily for the UI to get at the minimal amount of
state required to be a text editor. Subclasses will
return the actual type of the model which will typically
be something that extends Document.

Returns:

the model

setComponentOrientation

getActions

Suppressed: Fetches the command list for the editor. This is
the list of commands supported by the plugged-in UI
augmented by the collection of commands that the
editor itself supports. These are useful for binding
to events, such as in a keymap.

Returns:

the command list

setMargin

Enabled: Sets margin space between the text component's border
and its text. The text component's default Border
object will use this value to create the proper margin.
However, if a non-default border is set on the text component,
it is that Border object's responsibility to create the
appropriate margin space (else this property will effectively
be ignored). This causes a redraw of the component.
A PropertyChange event ("margin") is sent to all listeners.

getNavigationFilter

Enabled: Returns the NavigationFilter. NavigationFilter
is used by DefaultCaret and the default cursor movement
actions as a way to restrict the cursor movement. A null return value
implies the cursor movement and selection should not be restricted.

Returns:

the NavigationFilter

Since:

1.4

getCaret

setCaret

Enabled: Sets the caret to be used. By default this will be set
by the UI that gets installed. This can be changed to
a custom caret if desired. Setting the caret results in a
PropertyChange event ("caret") being fired.

getHighlighter

setHighlighter

Enabled: Sets the highlighter to be used. By default this will be set
by the UI that gets installed. This can be changed to
a custom highlighter if desired. The highlighter can be set to
null to disable it.
A PropertyChange event ("highlighter") is fired
when a new highlighter is installed.

setDragEnabled

public void setDragEnabled(boolean b)

Enabled: Sets the dragEnabled property,
which must be true to enable
automatic drag handling (the first part of drag and drop)
on this component.
The transferHandler property needs to be set
to a non-null value for the drag to do
anything. The default value of the dragEnabled
property
is false.

When automatic drag handling is enabled,
most look and feels begin a drag-and-drop operation
whenever the user presses the mouse button over a selection
and then moves the mouse a few pixels.
Setting this property to true
can therefore have a subtle effect on
how selections behave.

Some look and feels might not support automatic drag and drop;
they will ignore this property. You can work around such
look and feels by modifying the component
to directly call the exportAsDrag method of a
TransferHandler.

getKeymap

addKeymap

Suppressed: Adds a new keymap into the keymap hierarchy. Keymap bindings
resolve from bottom up so an attribute specified in a child
will override an attribute specified in the parent.

Parameters:

nm - the name of the keymap (must be unique within the
collection of named keymaps in the document); the name may
be null if the keymap is unnamed,
but the caller is responsible for managing the reference
returned as an unnamed keymap can't
be fetched by name

parent - the parent keymap; this may be null if
unspecified bindings need not be resolved in some other keymap

loadKeymap

Loads a keymap with a bunch of
bindings. This can be used to take a static table of
definitions and load them into some keymap. The following
example illustrates an example of binding some keys to
the cut, copy, and paste actions associated with a
JTextComponent. A code fragment to accomplish
this might look as follows:

isProcessInputMethodEventOverridden

Returns true if klass is NOT a JTextComponent and it or
one of its superclasses (stoping at JTextComponent) overrides
processInputMethodEvent. It is assumed this will be
invoked from within a doPrivileged, and it is also
assumed klass extends JTextComponent.

getSelectedTextColor

setSelectedTextColor

Enabled: Sets the current color used to render the selected text.
Setting the color to null is the same as
Color.black. Setting the color results in a
PropertyChange event ("selectedTextColor") being fired.

replaceSelection

Enabled: Replaces the currently selected content with new content
represented by the given string. If there is no selection
this amounts to an insert of the given text. If there
is no replacement text this amounts to a removal of the
current selection.

This is the method that is used by the default implementation
of the action for inserting content that gets bound to the
keymap actions.

This method is thread safe, although most Swing methods
are not. Please see
Threads
and Swing for more information.

modelToView

Enabled: Converts the given location in the model to a place in
the view coordinate system.
The component must have a positive size for
this translation to be computed (i.e. layout cannot
be computed until the component has been sized). The
component does not have to be visible or painted.

Parameters:

pos - the position >= 0

Returns:

the coordinates as a rectangle, with (r.x, r.y) as the location
in the coordinate system, or null if the component does
not yet have a positive size.

viewToModel

Enabled: Converts the given place in the view coordinate system
to the nearest representative location in the model.
The component must have a positive size for
this translation to be computed (i.e. layout cannot
be computed until the component has been sized). The
component does not have to be visible or painted.

Parameters:

pt - the location in the view to translate

Returns:

the offset >= 0 from the start of the document,
or -1 if the component does not yet have a positive
size.

See Also:

TextUI#viewToModel

cut

public void cut()

Suppressed: Transfers the currently selected range in the associated
text model to the system clipboard, removing the contents
from the model. The current selection is reset. Does nothing
for null selections.

See Also:

java.awt.Toolkit#getSystemClipboard,
java.awt.datatransfer.Clipboard

copy

public void copy()

Suppressed: Transfers the currently selected range in the associated
text model to the system clipboard, leaving the contents
in the text model. The current selection remains intact.
Does nothing for null selections.

See Also:

java.awt.Toolkit#getSystemClipboard,
java.awt.datatransfer.Clipboard

paste

public void paste()

Suppressed: Transfers the contents of the system clipboard into the
associated text model. If there is a selection in the
associated view, it is replaced with the contents of the
clipboard. If there is no selection, the clipboard contents
are inserted in front of the current insert position in
the associated view. If the clipboard is empty, does nothing.

invokeAction

This is a conveniance method that is only useful for
cut, copy and paste. If
an Action with the name name does not
exist in the ActionMap, this will attemp to install a
TransferHandler and then use altAction.

installDefaultTransferHandlerIfNecessary

private void installDefaultTransferHandlerIfNecessary()

If the current TransferHandler is null, this will
install a new one.

moveCaretPosition

public void moveCaretPosition(int pos)

Enabled: Moves the caret to a new position, leaving behind a mark
defined by the last time setCaretPosition was
called. This forms a selection.
If the document is null, does nothing. The position
must be between 0 and the length of the component's text or else
an exception is thrown.

setFocusAccelerator

public void setFocusAccelerator(char aKey)

Enabled: Sets the key accelerator that will cause the receiving text
component to get the focus. The accelerator will be the
key combination of the alt key and the character
given (converted to upper case). By default, there is no focus
accelerator key. Any previous key accelerator setting will be
superseded. A '\0' key setting will be registered, and has the
effect of turning off the focus accelerator. When the new key
is set, a PropertyChange event (FOCUS_ACCELERATOR_KEY) will be fired.

read

Enabled: Initializes from a stream. This creates a
model of the type appropriate for the component
and initializes the model from the stream.
By default this will load the model as plain
text. Previous contents of the model are discarded.

Parameters:

in - the stream to read from

desc - an object describing the stream; this
might be a string, a File, a URL, etc. Some kinds
of documents (such as html for example) might be
able to make use of this information; if non-null,
it is added as a property of the document

removeNotify

setCaretPosition

public void setCaretPosition(int position)

Enabled: Sets the position of the text insertion caret for the
TextComponent. Note that the caret tracks change,
so this may move if the underlying text of the component is changed.
If the document is null, does nothing. The position
must be between 0 and the length of the component's text or else
an exception is thrown.

Parameters:

position - the position

getCaretPosition

public int getCaretPosition()

Enabled: Returns the position of the text insertion caret for the
text component.

Returns:

the position of the text insertion caret for the
text component >= 0

setText

Enabled: Sets the text of this TextComponent
to the specified text. If the text is null
or empty, has the effect of simply deleting the old text.
When text has been inserted, the resulting caret location
is determined by the implementation of the caret class.

This method is thread safe, although most Swing methods
are not. Please see
Threads
and Swing for more information.

getSelectionStart

Enabled: Returns the selected text's start position. Return 0 for an
empty document, or the value of dot if no selection.

Returns:

the start position >= 0

setSelectionStart

public void setSelectionStart(int selectionStart)

Enabled: Sets the selection start to the specified position. The new
starting point is constrained to be before or at the current
selection end.

This is available for backward compatibility to code
that called this method on java.awt.TextComponent.
This is implemented to forward to the Caret
implementation which is where the actual selection is maintained.

Parameters:

selectionStart - the start position of the text >= 0

getSelectionEnd

public int getSelectionEnd()

Enabled: Returns the selected text's end position. Return 0 if the document
is empty, or the value of dot if there is no selection.

Returns:

the end position >= 0

setSelectionEnd

public void setSelectionEnd(int selectionEnd)

Enabled: Sets the selection end to the specified position. The new
end point is constrained to be at or after the current
selection start.

This is available for backward compatibility to code
that called this method on java.awt.TextComponent.
This is implemented to forward to the Caret
implementation which is where the actual selection is maintained.

Parameters:

selectionEnd - the end position of the text >= 0

select

public void select(int selectionStart,
int selectionEnd)

Enabled: Selects the text between the specified start and end positions.

This method sets the start and end positions of the
selected text, enforcing the restriction that the start position
must be greater than or equal to zero. The end position must be
greater than or equal to the start position, and less than or
equal to the length of the text component's text.

If the caller supplies values that are inconsistent or out of
bounds, the method enforces these constraints silently, and
without failure. Specifically, if the start position or end
position is greater than the length of the text, it is reset to
equal the text length. If the start position is less than zero,
it is reset to zero, and if the end position is less than the
start position, it is reset to the start position.

This call is provided for backward compatibility.
It is routed to a call to setCaretPosition
followed by a call to moveCaretPosition.
The preferred way to manage selection is by calling
those methods directly.

getScrollableUnitIncrement

Enabled: 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. Ideally,
components should handle a partially exposed row or column by
returning the distance required to completely expose the item.

The default implementation of this is to simply return 10% of
the visible area. Subclasses are likely to be able to provide
a much more reasonable value.

getScrollableTracksViewportWidth

public boolean getScrollableTracksViewportWidth()

Enabled: Returns true if a viewport should always force the width of this
Scrollable to match the width of the viewport.
For example a normal text view that supported line wrapping
would return true here, since it would be undesirable for
wrapped lines to disappear beyond the right
edge of the viewport. Note that returning true for a
Scrollable whose ancestor is a JScrollPane
effectively disables horizontal scrolling.

Scrolling containers, like JViewport,
will use this method each time they are validated.

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

getScrollableTracksViewportHeight

public boolean getScrollableTracksViewportHeight()

Enabled: Returns true if a viewport should always force the height of this
Scrollable to match the height of the viewport.
For example a columnar text view that flowed text in left to
right columns could effectively disable vertical scrolling by
returning true here.

Scrolling containers, like JViewport,
will use this method each time they are validated.

getAccessibleContext

Suppressed: Gets the AccessibleContext associated with this
JTextComponent. For text components,
the AccessibleContext takes the form of an
AccessibleJTextComponent.
A new AccessibleJTextComponent instance
is created if necessary.

paramString

Returns a string representation of this JTextComponent.
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.

Overriding paramString to provide information about the
specific new aspects of the JFC components.