Methods Summary |
---|
public void | addCaretListener(javax.swing.event.CaretListener listener)Adds a caret listener for notification of any changes
to the caret.
listenerList.add(CaretListener.class, listener);
|
public void | addInputMethodListener(java.awt.event.InputMethodListener l)
super.addInputMethodListener(l);
if (l != null) {
needToSendKeyTypedEvent = false;
checkedInputOverride = true;
}
|
public static javax.swing.text.Keymap | addKeymap(java.lang.String nm, javax.swing.text.Keymap parent)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.
Keymap map = new DefaultKeymap(nm, parent);
if (nm != null) {
// add a named keymap, a class of bindings
getKeymapTable().put(nm, map);
}
return map;
|
boolean | composedTextExists()
return (composedTextStart != null);
|
public void | copy()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.
invokeAction("copy", TransferHandler.getCopyAction());
|
private void | createComposedTextAttribute(int composedIndex, java.text.AttributedCharacterIterator text)
Document doc = getDocument();
StringBuffer strBuf = new StringBuffer();
// create attributed string with no attributes
for (char c = text.setIndex(composedIndex);
c != CharacterIterator.DONE; c = text.next()) {
strBuf.append(c);
}
composedTextContent = new String(strBuf);
composedTextAttribute = new SimpleAttributeSet();
composedTextAttribute.addAttribute(StyleConstants.ComposedTextAttribute,
new AttributedString(text, composedIndex, text.getEndIndex()));
|
public void | cut()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.
if (isEditable() && isEnabled()) {
invokeAction("cut", TransferHandler.getCutAction());
}
|
private void | exchangeCaret(javax.swing.text.Caret oldCaret, javax.swing.text.Caret newCaret)
int blinkRate = oldCaret.getBlinkRate();
setCaret(newCaret);
caret.setBlinkRate(blinkRate);
caret.setVisible(hasFocus());
|
protected void | fireCaretUpdate(javax.swing.event.CaretEvent e)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.
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==CaretListener.class) {
((CaretListener)listeners[i+1]).caretUpdate(e);
}
}
|
public javax.accessibility.AccessibleContext | getAccessibleContext()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.
if (accessibleContext == null) {
accessibleContext = new AccessibleJTextComponent();
}
return accessibleContext;
|
public javax.swing.Action[] | getActions()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.
return getUI().getEditorKit(this).getActions();
|
public javax.swing.text.Caret | getCaret()Fetches the caret that allows text-oriented navigation over
the view.
return caret;
|
public java.awt.Color | getCaretColor()Fetches the current color used to render the
caret.
return caretColor;
|
public javax.swing.event.CaretListener[] | getCaretListeners()Returns an array of all the caret listeners
registered on this text component.
return (CaretListener[])listenerList.getListeners(CaretListener.class);
|
public int | getCaretPosition()Returns the position of the text insertion caret for the
text component.
return caret.getDot();
|
private int | getCurrentEventModifiers()
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
return modifiers;
|
public java.awt.Color | getDisabledTextColor()Fetches the current color used to render the
selected text.
return disabledTextColor;
|
public javax.swing.text.Document | getDocument()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.
return model;
|
public boolean | getDragEnabled()Gets the dragEnabled property.
return dragEnabled;
|
public char | getFocusAccelerator()Returns the key accelerator that will cause the receiving
text component to get the focus. Return '\0' if no focus
accelerator has been set.
return focusAccelerator;
|
static final javax.swing.text.JTextComponent | getFocusedComponent()Returns the JTextComponent that most recently had focus. The returned
value may currently have focus.
return (JTextComponent)AppContext.getAppContext().
get(FOCUSED_COMPONENT);
|
public javax.swing.text.Highlighter | getHighlighter()Fetches the object responsible for making highlights.
return highlighter;
|
public java.awt.im.InputMethodRequests | getInputMethodRequests()
if (inputMethodRequestsHandler == null) {
inputMethodRequestsHandler =
(InputMethodRequests)new InputMethodRequestsHandler();
Document doc = getDocument();
if (doc != null) {
doc.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
}
}
return inputMethodRequestsHandler;
|
public javax.swing.text.Keymap | getKeymap()Fetches the keymap currently active in this text
component.
return keymap;
|
public static javax.swing.text.Keymap | getKeymap(java.lang.String nm)Fetches a named keymap previously added to the document.
This does not work with null -named keymaps.
return getKeymapTable().get(nm);
|
private static java.util.HashMap | getKeymapTable()
AppContext appContext = AppContext.getAppContext();
HashMap<String,Keymap> keymapTable =
(HashMap<String,Keymap>)appContext.get(KEYMAP_TABLE);
if (keymapTable == null) {
keymapTable = new HashMap<String,Keymap>(17);
appContext.put(KEYMAP_TABLE, keymapTable);
//initialize default keymap
Keymap binding = addKeymap(DEFAULT_KEYMAP, null);
binding.setDefaultAction(new
DefaultEditorKit.DefaultKeyTypedAction());
}
return keymapTable;
|
public java.awt.Insets | getMargin()Returns the margin between the text component's border and
its text.
return margin;
|
public javax.swing.text.NavigationFilter | getNavigationFilter()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.
return navigationFilter;
|
public java.awt.Dimension | getPreferredScrollableViewportSize()Returns the preferred size of the viewport for a view component.
This is implemented to do the default behavior of returning
the preferred size of the component.
return getPreferredSize();
|
public int | getScrollableBlockIncrement(java.awt.Rectangle visibleRect, int orientation, int direction)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.
The default implementation of this is to simply return the visible
area. Subclasses will likely be able to provide a much more
reasonable value.
switch(orientation) {
case SwingConstants.VERTICAL:
return visibleRect.height;
case SwingConstants.HORIZONTAL:
return visibleRect.width;
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
|
public boolean | getScrollableTracksViewportHeight()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.
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
}
return false;
|
public boolean | getScrollableTracksViewportWidth()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.
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
return false;
|
public int | getScrollableUnitIncrement(java.awt.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. 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.
switch(orientation) {
case SwingConstants.VERTICAL:
return visibleRect.height / 10;
case SwingConstants.HORIZONTAL:
return visibleRect.width / 10;
default:
throw new IllegalArgumentException("Invalid orientation: " + orientation);
}
|
public java.lang.String | getSelectedText()Returns the selected text contained in this
TextComponent . If the selection is
null or the document empty, returns null .
String txt = null;
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
if (p0 != p1) {
try {
Document doc = getDocument();
txt = doc.getText(p0, p1 - p0);
} catch (BadLocationException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
return txt;
|
public java.awt.Color | getSelectedTextColor()Fetches the current color used to render the
selected text.
return selectedTextColor;
|
public java.awt.Color | getSelectionColor()Fetches the current color used to render the
selection.
return selectionColor;
|
public int | getSelectionEnd()Returns the selected text's end position. Return 0 if the document
is empty, or the value of dot if there is no selection.
int end = Math.max(caret.getDot(), caret.getMark());
return end;
|
public int | getSelectionStart()Returns the selected text's start position. Return 0 for an
empty document, or the value of dot if no selection.
int start = Math.min(caret.getDot(), caret.getMark());
return start;
|
public java.lang.String | getText(int offs, int len)Fetches a portion of the text represented by the
component. Returns an empty string if length is 0.
return getDocument().getText(offs, len);
|
public java.lang.String | getText()Returns the text contained in this TextComponent .
If the underlying document is null ,
will give a NullPointerException .
Note that text is not a bound property, so no PropertyChangeEvent
is fired when it changes. To listen for changes to the text,
use DocumentListener .
Document doc = getDocument();
String txt;
try {
txt = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
txt = null;
}
return txt;
|
public java.lang.String | getToolTipText(java.awt.event.MouseEvent event)Returns the string to be used as the tooltip for event .
This will return one of:
- If
setToolTipText has been invoked with a
non-null
value, it will be returned, otherwise
- The value from invoking
getToolTipText on
the UI will be returned.
By default JTextComponent does not register
itself with the ToolTipManager .
This means that tooltips will NOT be shown from the
TextUI unless registerComponent has
been invoked on the ToolTipManager .
String retValue = super.getToolTipText(event);
if (retValue == null) {
TextUI ui = getUI();
if (ui != null) {
retValue = ui.getToolTipText(this, new Point(event.getX(),
event.getY()));
}
}
return retValue;
|
public javax.swing.plaf.TextUI | getUI()Fetches the user-interface factory for this text-oriented editor. return (TextUI)ui;
|
private void | installDefaultTransferHandlerIfNecessary()If the current TransferHandler is null, this will
install a new one.
if (getTransferHandler() == null) {
if (defaultTransferHandler == null) {
defaultTransferHandler = new DefaultTransferHandler();
}
setTransferHandler(defaultTransferHandler);
}
|
private void | invokeAction(java.lang.String name, javax.swing.Action altAction)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 .
ActionMap map = getActionMap();
Action action = null;
if (map != null) {
action = map.get(name);
}
if (action == null) {
installDefaultTransferHandlerIfNecessary();
action = altAction;
}
action.actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, (String)action.
getValue(Action.NAME),
EventQueue.getMostRecentEventTime(),
getCurrentEventModifiers()));
|
public boolean | isEditable()Returns the boolean indicating whether this
TextComponent is editable or not.
return editable;
|
private static java.lang.Boolean | isProcessInputMethodEventOverridden(java.lang.Class klass)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 .
if (klass == JTextComponent.class) {
return Boolean.FALSE;
}
Boolean retValue = (Boolean)overrideMap.get(klass.getName());
if (retValue != null) {
return retValue;
}
Boolean sOverriden = isProcessInputMethodEventOverridden(
klass.getSuperclass());
if (sOverriden.booleanValue()) {
// If our superclass has overriden it, then by definition klass
// overrides it.
overrideMap.put(klass.getName(), sOverriden);
return sOverriden;
}
// klass's superclass didn't override it, check for an override in
// klass.
try {
Class[] classes = new Class[1];
classes[0] = InputMethodEvent.class;
Method m = klass.getDeclaredMethod("processInputMethodEvent",
classes);
retValue = Boolean.TRUE;
} catch (NoSuchMethodException nsme) {
retValue = Boolean.FALSE;
}
overrideMap.put(klass.getName(), retValue);
return retValue;
|
private boolean | isProcessInputMethodEventOverridden()
if (overrideMap == null) {
overrideMap = Collections.synchronizedMap(new HashMap());
}
Boolean retValue = (Boolean)overrideMap.get(getClass().getName());
if (retValue != null) {
return retValue.booleanValue();
}
Boolean ret = (Boolean)AccessController.doPrivileged(new
PrivilegedAction() {
public Object run() {
return isProcessInputMethodEventOverridden(
JTextComponent.this.getClass());
}
});
return ret.booleanValue();
|
public static void | loadKeymap(javax.swing.text.Keymap map, javax.swing.text.JTextComponent$KeyBinding[] bindings, javax.swing.Action[] actions)
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:
static final JTextComponent.KeyBinding[] defaultBindings = {
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),
DefaultEditorKit.copyAction),
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
DefaultEditorKit.pasteAction),
new JTextComponent.KeyBinding(
KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK),
DefaultEditorKit.cutAction),
};
JTextComponent c = new JTextPane();
Keymap k = c.getKeymap();
JTextComponent.loadKeymap(k, defaultBindings, c.getActions());
The sets of bindings and actions may be empty but must be
non-null .
Hashtable h = new Hashtable();
for (int i = 0; i < actions.length; i++) {
Action a = actions[i];
String value = (String)a.getValue(Action.NAME);
h.put((value!=null ? value:""), a);
}
for (int i = 0; i < bindings.length; i++) {
Action a = (Action) h.get(bindings[i].actionName);
if (a != null) {
map.addActionForKeyStroke(bindings[i].key, a);
}
}
|
private void | mapCommittedTextToAction(java.lang.String committedText)
Keymap binding = getKeymap();
if (binding != null) {
Action a = null;
if (committedText.length() == 1) {
KeyStroke k = KeyStroke.getKeyStroke(committedText.charAt(0));
a = binding.getAction(k);
}
if (a == null) {
a = binding.getDefaultAction();
}
if (a != null) {
ActionEvent ae =
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
committedText,
EventQueue.getMostRecentEventTime(),
getCurrentEventModifiers());
a.actionPerformed(ae);
}
}
|
public java.awt.Rectangle | modelToView(int pos)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.
return getUI().modelToView(this, pos);
|
public void | moveCaretPosition(int pos)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.
Document doc = getDocument();
if (doc != null) {
if (pos > doc.getLength() || pos < 0) {
throw new IllegalArgumentException("bad position: " + pos);
}
caret.moveDot(pos);
}
|
protected java.lang.String | 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.
String editableString = (editable ?
"true" : "false");
String caretColorString = (caretColor != null ?
caretColor.toString() : "");
String selectionColorString = (selectionColor != null ?
selectionColor.toString() : "");
String selectedTextColorString = (selectedTextColor != null ?
selectedTextColor.toString() : "");
String disabledTextColorString = (disabledTextColor != null ?
disabledTextColor.toString() : "");
String marginString = (margin != null ?
margin.toString() : "");
return super.paramString() +
",caretColor=" + caretColorString +
",disabledTextColor=" + disabledTextColorString +
",editable=" + editableString +
",margin=" + marginString +
",selectedTextColor=" + selectedTextColorString +
",selectionColor=" + selectionColorString;
|
public void | paste()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.
if (isEditable() && isEnabled()) {
invokeAction("paste", TransferHandler.getPasteAction());
}
|
protected void | processInputMethodEvent(java.awt.event.InputMethodEvent e)
// let listeners handle the events
super.processInputMethodEvent(e);
if (!e.isConsumed()) {
if (! isEditable()) {
return;
} else {
switch (e.getID()) {
case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
replaceInputMethodText(e);
// fall through
case InputMethodEvent.CARET_POSITION_CHANGED:
setInputMethodCaretPosition(e);
break;
}
}
e.consume();
}
|
public void | read(java.io.Reader in, java.lang.Object desc)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.
EditorKit kit = getUI().getEditorKit(this);
Document doc = kit.createDefaultDocument();
if (desc != null) {
doc.putProperty(Document.StreamDescriptionProperty, desc);
}
try {
kit.read(in, doc, 0);
setDocument(doc);
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
}
|
private void | readObject(java.io.ObjectInputStream s)
s.defaultReadObject();
caretEvent = new MutableCaretEvent(this);
addMouseListener(caretEvent);
addFocusListener(caretEvent);
|
public void | removeCaretListener(javax.swing.event.CaretListener listener)Removes a caret listener.
listenerList.remove(CaretListener.class, listener);
|
public static javax.swing.text.Keymap | removeKeymap(java.lang.String nm)Removes a named keymap previously added to the document. Keymaps
with null names may not be removed in this way.
return getKeymapTable().remove(nm);
|
public void | removeNotify()
super.removeNotify();
if (getFocusedComponent() == this) {
AppContext.getAppContext().remove(FOCUSED_COMPONENT);
}
|
private void | replaceInputMethodText(java.awt.event.InputMethodEvent e)
int commitCount = e.getCommittedCharacterCount();
AttributedCharacterIterator text = e.getText();
int composedTextIndex;
// old composed text deletion
Document doc = getDocument();
if (composedTextExists()) {
try {
doc.remove(composedTextStart.getOffset(),
composedTextEnd.getOffset() -
composedTextStart.getOffset());
} catch (BadLocationException ble) {}
composedTextStart = composedTextEnd = null;
composedTextAttribute = null;
composedTextContent = null;
}
if (text != null) {
text.first();
int committedTextStartIndex = 0;
int committedTextEndIndex = 0;
// committed text insertion
if (commitCount > 0) {
// Remember latest committed text start index
committedTextStartIndex = caret.getDot();
// Need to generate KeyTyped events for the committed text for components
// that are not aware they are active input method clients.
if (shouldSynthensizeKeyEvents()) {
for (char c = text.current(); commitCount > 0;
c = text.next(), commitCount--) {
KeyEvent ke = new KeyEvent(this, KeyEvent.KEY_TYPED,
EventQueue.getMostRecentEventTime(),
0, KeyEvent.VK_UNDEFINED, c);
processKeyEvent(ke);
}
} else {
StringBuffer strBuf = new StringBuffer();
for (char c = text.current(); commitCount > 0;
c = text.next(), commitCount--) {
strBuf.append(c);
}
// map it to an ActionEvent
mapCommittedTextToAction(new String(strBuf));
}
// Remember latest committed text end index
committedTextEndIndex = caret.getDot();
}
// new composed text insertion
composedTextIndex = text.getIndex();
if (composedTextIndex < text.getEndIndex()) {
createComposedTextAttribute(composedTextIndex, text);
try {
replaceSelection(null);
doc.insertString(caret.getDot(), composedTextContent,
composedTextAttribute);
composedTextStart = doc.createPosition(caret.getDot() -
composedTextContent.length());
composedTextEnd = doc.createPosition(caret.getDot());
} catch (BadLocationException ble) {
composedTextStart = composedTextEnd = null;
composedTextAttribute = null;
composedTextContent = null;
}
}
// Save the latest committed text information
if (committedTextStartIndex != committedTextEndIndex) {
try {
latestCommittedTextStart = doc.
createPosition(committedTextStartIndex);
latestCommittedTextEnd = doc.
createPosition(committedTextEndIndex);
} catch (BadLocationException ble) {
latestCommittedTextStart =
latestCommittedTextEnd = null;
}
} else {
latestCommittedTextStart =
latestCommittedTextEnd = null;
}
}
|
public void | replaceSelection(java.lang.String content)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.
Document doc = getDocument();
if (doc != null) {
try {
boolean composedTextSaved = saveComposedText(caret.getDot());
int p0 = Math.min(caret.getDot(), caret.getMark());
int p1 = Math.max(caret.getDot(), caret.getMark());
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(p0, p1 - p0, content,null);
}
else {
if (p0 != p1) {
doc.remove(p0, p1 - p0);
}
if (content != null && content.length() > 0) {
doc.insertString(p0, content, null);
}
}
if (composedTextSaved) {
restoreComposedText();
}
} catch (BadLocationException e) {
UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
}
}
|
private void | restoreComposedText()
Document doc = getDocument();
try {
doc.insertString(caret.getDot(),
composedTextContent,
composedTextAttribute);
composedTextStart = doc.createPosition(caret.getDot() -
composedTextContent.length());
composedTextEnd = doc.createPosition(caret.getDot());
} catch (BadLocationException ble) {}
|
private boolean | saveComposedText(int pos)
if (composedTextExists()) {
int start = composedTextStart.getOffset();
int len = composedTextEnd.getOffset() -
composedTextStart.getOffset();
if (pos >= start && pos <= start + len) {
try {
getDocument().remove(start, len);
return true;
} catch (BadLocationException ble) {}
}
}
return false;
|
public void | select(int selectionStart, int selectionEnd)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.
// argument adjustment done by java.awt.TextComponent
int docLength = getDocument().getLength();
if (selectionStart < 0) {
selectionStart = 0;
}
if (selectionStart > docLength) {
selectionStart = docLength;
}
if (selectionEnd > docLength) {
selectionEnd = docLength;
}
if (selectionEnd < selectionStart) {
selectionEnd = selectionStart;
}
setCaretPosition(selectionStart);
moveCaretPosition(selectionEnd);
|
public void | selectAll()Selects all the text in the TextComponent .
Does nothing on a null or empty document.
Document doc = getDocument();
if (doc != null) {
setCaretPosition(0);
moveCaretPosition(doc.getLength());
}
|
public void | setCaret(javax.swing.text.Caret c)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.
if (caret != null) {
caret.removeChangeListener(caretEvent);
caret.deinstall(this);
}
Caret old = caret;
caret = c;
if (caret != null) {
caret.install(this);
caret.addChangeListener(caretEvent);
}
firePropertyChange("caret", old, caret);
|
public void | setCaretColor(java.awt.Color c)Sets the current color used to render the caret.
Setting to null effectively restores the default color.
Setting the color results in a PropertyChange event ("caretColor")
being fired.
Color old = caretColor;
caretColor = c;
firePropertyChange("caretColor", old, caretColor);
|
public void | setCaretPosition(int position)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.
Document doc = getDocument();
if (doc != null) {
if (position > doc.getLength() || position < 0) {
throw new IllegalArgumentException("bad position: " + position);
}
caret.setDot(position);
}
|
public void | setComponentOrientation(java.awt.ComponentOrientation o)
// Set the document's run direction property to match the
// ComponentOrientation property.
Document doc = getDocument();
if( doc != null ) {
Boolean runDir = o.isLeftToRight()
? TextAttribute.RUN_DIRECTION_LTR
: TextAttribute.RUN_DIRECTION_RTL;
doc.putProperty( TextAttribute.RUN_DIRECTION, runDir );
}
super.setComponentOrientation( o );
|
public void | setDisabledTextColor(java.awt.Color c)Sets the current color used to render the
disabled text. Setting the color fires off a
PropertyChange event ("disabledTextColor").
Color old = disabledTextColor;
disabledTextColor = c;
firePropertyChange("disabledTextColor", old, disabledTextColor);
|
public void | setDocument(javax.swing.text.Document doc)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.
Document old = model;
/*
* aquire a read lock on the old model to prevent notification of
* mutations while we disconnecting the old model.
*/
try {
if (old instanceof AbstractDocument) {
((AbstractDocument)old).readLock();
}
if (accessibleContext != null) {
model.removeDocumentListener(
((AccessibleJTextComponent)accessibleContext));
}
if (inputMethodRequestsHandler != null) {
model.removeDocumentListener((DocumentListener)inputMethodRequestsHandler);
}
model = doc;
// Set the document's run direction property to match the
// component's ComponentOrientation property.
Boolean runDir = getComponentOrientation().isLeftToRight()
? TextAttribute.RUN_DIRECTION_LTR
: TextAttribute.RUN_DIRECTION_RTL;
doc.putProperty( TextAttribute.RUN_DIRECTION, runDir );
firePropertyChange("document", old, doc);
} finally {
if (old instanceof AbstractDocument) {
((AbstractDocument)old).readUnlock();
}
}
revalidate();
repaint();
if (accessibleContext != null) {
model.addDocumentListener(
((AccessibleJTextComponent)accessibleContext));
}
if (inputMethodRequestsHandler != null) {
model.addDocumentListener((DocumentListener)inputMethodRequestsHandler);
}
|
public void | setDragEnabled(boolean b)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 .
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
|
public void | setEditable(boolean b)Sets the specified boolean to indicate whether or not this
TextComponent should be editable.
A PropertyChange event ("editable") is fired when the
state is changed.
if (b != editable) {
boolean oldVal = editable;
editable = b;
if (editable) {
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
} else {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
enableInputMethods(editable);
firePropertyChange("editable", Boolean.valueOf(oldVal), Boolean.valueOf(editable));
repaint();
}
|
public void | setFocusAccelerator(char aKey)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.
aKey = Character.toUpperCase(aKey);
char old = focusAccelerator;
focusAccelerator = aKey;
// Fix for 4341002: value of FOCUS_ACCELERATOR_KEY is wrong.
// So we fire both FOCUS_ACCELERATOR_KEY, for compatibility,
// and the correct event here.
firePropertyChange(FOCUS_ACCELERATOR_KEY, old, focusAccelerator);
firePropertyChange("focusAccelerator", old, focusAccelerator);
|
public void | setHighlighter(javax.swing.text.Highlighter h)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.
if (highlighter != null) {
highlighter.deinstall(this);
}
Highlighter old = highlighter;
highlighter = h;
if (highlighter != null) {
highlighter.install(this);
}
firePropertyChange("highlighter", old, h);
|
private void | setInputMethodCaretPosition(java.awt.event.InputMethodEvent e)
int dot;
if (composedTextExists()) {
dot = composedTextStart.getOffset();
if (!(caret instanceof ComposedTextCaret)) {
if (composedTextCaret == null) {
composedTextCaret = new ComposedTextCaret();
}
originalCaret = caret;
// Sets composed text caret
exchangeCaret(originalCaret, composedTextCaret);
}
TextHitInfo caretPos = e.getCaret();
if (caretPos != null) {
int index = caretPos.getInsertionIndex();
dot += index;
if (index == 0) {
// Scroll the component if needed so that the composed text
// becomes visible.
try {
Rectangle d = modelToView(dot);
Rectangle end = modelToView(composedTextEnd.getOffset());
Rectangle b = getBounds();
d.x += Math.min(end.x - d.x, b.width);
scrollRectToVisible(d);
} catch (BadLocationException ble) {}
}
}
caret.setDot(dot);
} else if (caret instanceof ComposedTextCaret) {
dot = caret.getDot();
// Restores original caret
exchangeCaret(caret, originalCaret);
caret.setDot(dot);
}
|
public void | setKeymap(javax.swing.text.Keymap map)Sets the keymap to use for binding events to
actions. Setting to null effectively disables
keyboard input.
A PropertyChange event ("keymap") is fired when a new keymap
is installed.
Keymap old = keymap;
keymap = map;
firePropertyChange("keymap", old, keymap);
updateInputMap(old, map);
|
public void | setMargin(java.awt.Insets m)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.
Insets old = margin;
margin = m;
firePropertyChange("margin", old, m);
invalidate();
|
public void | setNavigationFilter(javax.swing.text.NavigationFilter filter)Sets the NavigationFilter . NavigationFilter
is used by DefaultCaret and the default cursor movement
actions as a way to restrict the cursor movement.
navigationFilter = filter;
|
public void | setSelectedTextColor(java.awt.Color c)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.
Color old = selectedTextColor;
selectedTextColor = c;
firePropertyChange("selectedTextColor", old, selectedTextColor);
|
public void | setSelectionColor(java.awt.Color c)Sets the current color used to render the selection.
Setting the color to null is the same as setting
Color.white . Setting the color results in a
PropertyChange event ("selectionColor").
Color old = selectionColor;
selectionColor = c;
firePropertyChange("selectionColor", old, selectionColor);
|
public void | setSelectionEnd(int selectionEnd)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.
/* Route through select method to enforce consistent policy
* between selectionStart and selectionEnd.
*/
select(getSelectionStart(), selectionEnd);
|
public void | setSelectionStart(int selectionStart)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.
/* Route through select method to enforce consistent policy
* between selectionStart and selectionEnd.
*/
select(selectionStart, getSelectionEnd());
|
public void | setText(java.lang.String t)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.
Note that text is not a bound property, so no PropertyChangeEvent
is fired when it changes. To listen for changes to the text,
use DocumentListener .
try {
Document doc = getDocument();
if (doc instanceof AbstractDocument) {
((AbstractDocument)doc).replace(0, doc.getLength(), t,null);
}
else {
doc.remove(0, doc.getLength());
doc.insertString(0, t, null);
}
} catch (BadLocationException e) {
UIManager.getLookAndFeel().provideErrorFeedback(JTextComponent.this);
}
|
public void | setUI(javax.swing.plaf.TextUI ui)Sets the user-interface factory for this text-oriented editor.
super.setUI(ui);
|
private boolean | shouldSynthensizeKeyEvents()Returns true if KeyEvents should be synthesized from an InputEvent.
if (!checkedInputOverride) {
checkedInputOverride = true;
needToSendKeyTypedEvent =
!isProcessInputMethodEventOverridden();
}
return needToSendKeyTypedEvent;
|
void | updateInputMap(javax.swing.text.Keymap oldKm, javax.swing.text.Keymap newKm)Updates the InputMap s in response to a
Keymap change.
// Locate the current KeymapWrapper.
InputMap km = getInputMap(JComponent.WHEN_FOCUSED);
InputMap last = km;
while (km != null && !(km instanceof KeymapWrapper)) {
last = km;
km = km.getParent();
}
if (km != null) {
// Found it, tweak the InputMap that points to it, as well
// as anything it points to.
if (newKm == null) {
if (last != km) {
last.setParent(km.getParent());
}
else {
last.setParent(null);
}
}
else {
InputMap newKM = new KeymapWrapper(newKm);
last.setParent(newKM);
if (last != km) {
newKM.setParent(km.getParent());
}
}
}
else if (newKm != null) {
km = getInputMap(JComponent.WHEN_FOCUSED);
if (km != null) {
// Couldn't find it.
// Set the parent of WHEN_FOCUSED InputMap to be the new one.
InputMap newKM = new KeymapWrapper(newKm);
newKM.setParent(km.getParent());
km.setParent(newKM);
}
}
// Do the same thing with the ActionMap
ActionMap am = getActionMap();
ActionMap lastAM = am;
while (am != null && !(am instanceof KeymapActionMap)) {
lastAM = am;
am = am.getParent();
}
if (am != null) {
// Found it, tweak the Actionap that points to it, as well
// as anything it points to.
if (newKm == null) {
if (lastAM != am) {
lastAM.setParent(am.getParent());
}
else {
lastAM.setParent(null);
}
}
else {
ActionMap newAM = new KeymapActionMap(newKm);
lastAM.setParent(newAM);
if (lastAM != am) {
newAM.setParent(am.getParent());
}
}
}
else if (newKm != null) {
am = getActionMap();
if (am != null) {
// Couldn't find it.
// Set the parent of ActionMap to be the new one.
ActionMap newAM = new KeymapActionMap(newKm);
newAM.setParent(am.getParent());
am.setParent(newAM);
}
}
|
public void | updateUI()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.
setUI((TextUI)UIManager.getUI(this));
invalidate();
|
public int | viewToModel(java.awt.Point pt)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.
return getUI().viewToModel(this, pt);
|
public void | write(java.io.Writer out)Stores the contents of the model into the given
stream. By default this will store the model as plain
text.
Document doc = getDocument();
try {
getUI().getEditorKit(this).write(out, doc, 0, doc.getLength());
} catch (BadLocationException e) {
throw new IOException(e.getMessage());
}
|