Method from javax.swing.text.DefaultCaret Detail: |
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
Adds a listener to track whenever the caret position has
been changed. |
void adjustCaretAndFocus(MouseEvent e) {
adjustCaret(e);
adjustFocus(false);
}
|
protected void adjustVisibility(Rectangle nloc) {
if(component == null) {
return;
}
if (SwingUtilities.isEventDispatchThread()) {
component.scrollRectToVisible(nloc);
} else {
SwingUtilities.invokeLater(new SafeScroller(nloc));
}
}
Scrolls the associated view (if necessary) to make
the caret visible. Since how this should be done
is somewhat of a policy, this method can be
reimplemented to change the behavior. By default
the scrollRectToVisible method is called on the
associated component. |
void changeCaretPosition(int dot,
Bias dotBias) {
// repaint the old position and set the new value of
// the dot.
repaint();
// Make sure the caret is visible if this window has the focus.
if (flasher != null && flasher.isRunning()) {
visible = true;
flasher.restart();
}
// notify listeners at the caret moved
this.dot = dot;
this.dotBias = dotBias;
dotLTR = isPositionLTR(dot, dotBias);
fireStateChanged();
updateSystemSelection();
setMagicCaretPosition(null);
// We try to repaint the caret later, since things
// may be unstable at the time this is called
// (i.e. we don't want to depend upon notification
// order or the fact that this might happen on
// an unsafe thread).
Runnable callRepaintNewCaret = new Runnable() {
public void run() {
repaintNewCaret();
}
};
SwingUtilities.invokeLater(callRepaintNewCaret);
}
Sets the caret position (dot) to a new location. This
causes the old and new location to be repainted. It
also makes sure that the caret is within the visible
region of the view, if the view is scrollable. |
protected synchronized void damage(Rectangle r) {
if (r != null) {
int damageWidth = getCaretWidth(r.height);
x = r.x - 4 - (damageWidth > > 1);
y = r.y;
width = 9 + damageWidth;
height = r.height;
repaint();
}
}
Damages the area surrounding the caret to cause
it to be repainted in a new location. If paint()
is reimplemented, this method should also be
reimplemented. This method should update the
caret bounds (x, y, width, and height). |
public void deinstall(JTextComponent c) {
c.removeMouseListener(this);
c.removeMouseMotionListener(this);
c.removeFocusListener(this);
c.removePropertyChangeListener(handler);
Document doc = c.getDocument();
if (doc != null) {
doc.removeDocumentListener(handler);
}
synchronized(this) {
component = null;
}
if (flasher != null) {
flasher.stop();
}
}
Called when the UI is being removed from the
interface of a JTextComponent. This is used to
unregister any listeners that were attached. |
public boolean equals(Object obj) {
return (this == obj);
}
Compares this object to the specified object.
The superclass behavior of comparing rectangles
is not desired, so this is changed to the Object
behavior. |
protected void fireStateChanged() {
// 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]==ChangeListener.class) {
// Lazily create the event:
if (changeEvent == null)
changeEvent = new ChangeEvent(this);
((ChangeListener)listeners[i+1]).stateChanged(changeEvent);
}
}
}
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 last to first. |
public void focusGained(FocusEvent e) {
if (component.isEnabled()) {
if (component.isEditable()) {
setVisible(true);
}
setSelectionVisible(true);
}
}
Called when the component containing the caret gains
focus. This is implemented to set the caret to visible
if the component is editable. |
public void focusLost(FocusEvent e) {
setVisible(false);
setSelectionVisible(ownsSelection || e.isTemporary());
}
Called when the component containing the caret loses
focus. This is implemented to set the caret to visibility
to false. |
public int getBlinkRate() {
return (flasher == null) ? 0 : flasher.getDelay();
}
Gets the caret blink rate. |
int getCaretWidth(int height) {
if (aspectRatio > -1) {
return (int) (aspectRatio * height) + 1;
}
if (caretWidth > -1) {
return caretWidth;
}
return 1;
}
|
public ChangeListener[] getChangeListeners() {
return listenerList.getListeners(ChangeListener.class);
}
Returns an array of all the change listeners
registered on this caret. |
protected final JTextComponent getComponent() {
return component;
}
Gets the text editor component that this caret is
is bound to. |
public int getDot() {
return dot;
}
Fetches the current position of the caret. |
public Bias getDotBias() {
return dotBias;
}
Returns the bias of the caret position. |
public T[] getListeners(Class<T> listenerType) {
return listenerList.getListeners(listenerType);
}
Returns an array of all the objects currently registered
as FooListener s
upon this caret.
FooListener s are registered using the
addFooListener method.
You can specify the listenerType argument
with a class literal,
such as
FooListener.class .
For example, you can query a
DefaultCaret c
for its change listeners with the following code:
ChangeListener[] cls = (ChangeListener[])(c.getListeners(ChangeListener.class));
If no such listeners exist, this method returns an empty array. |
public Point getMagicCaretPosition() {
return magicCaretPosition;
}
Gets the saved caret position. |
public int getMark() {
return mark;
}
Fetches the current position of the mark. If there is a selection,
the dot and mark will not be the same. |
public Bias getMarkBias() {
return markBias;
}
Returns the bias of the mark. |
protected HighlightPainter getSelectionPainter() {
return DefaultHighlighter.DefaultPainter;
}
Gets the painter for the Highlighter. |
public int getUpdatePolicy() {
return updatePolicy;
}
Gets the caret movement policy on document updates. |
Bias guessBiasForOffset(int offset,
Bias lastBias,
boolean lastLTR) {
// There is an abiguous case here. That if your model looks like:
// abAB with the cursor at abB]A (visual representation of
// 3 forward) deleting could either become abB] or
// ab[B. I'ld actually prefer abB]. But, if I implement that
// a delete at abBA] would result in aBA] vs a[BA which I
// think is totally wrong. To get this right we need to know what
// was deleted. And we could get this from the bidi structure
// in the change event. So:
// PENDING: base this off what was deleted.
if(lastLTR != isPositionLTR(offset, lastBias)) {
lastBias = Position.Bias.Backward;
}
else if(lastBias != Position.Bias.Backward &&
lastLTR != isPositionLTR(offset, Position.Bias.Backward)) {
lastBias = Position.Bias.Backward;
}
if (lastBias == Position.Bias.Backward && offset > 0) {
try {
Segment s = new Segment();
component.getDocument().getText(offset - 1, 1, s);
if (s.count > 0 && s.array[s.offset] == '\n') {
lastBias = Position.Bias.Forward;
}
}
catch (BadLocationException ble) {}
}
return lastBias;
}
|
void handleMoveDot(int dot,
Bias dotBias) {
changeCaretPosition(dot, dotBias);
if (selectionVisible) {
Highlighter h = component.getHighlighter();
if (h != null) {
int p0 = Math.min(dot, mark);
int p1 = Math.max(dot, mark);
// if p0 == p1 then there should be no highlight, remove it if necessary
if (p0 == p1) {
if (selectionTag != null) {
h.removeHighlight(selectionTag);
selectionTag = null;
}
// otherwise, change or add the highlight
} else {
try {
if (selectionTag != null) {
h.changeHighlight(selectionTag, p0, p1);
} else {
Highlighter.HighlightPainter p = getSelectionPainter();
selectionTag = h.addHighlight(p0, p1, p);
}
} catch (BadLocationException e) {
throw new StateInvariantError("Bad caret position");
}
}
}
}
}
|
void handleSetDot(int dot,
Bias dotBias) {
// move dot, if it changed
Document doc = component.getDocument();
if (doc != null) {
dot = Math.min(dot, doc.getLength());
}
dot = Math.max(dot, 0);
// The position (0,Backward) is out of range so disallow it.
if( dot == 0 )
dotBias = Position.Bias.Forward;
mark = dot;
if (this.dot != dot || this.dotBias != dotBias ||
selectionTag != null || forceCaretPositionChange) {
changeCaretPosition(dot, dotBias);
}
this.markBias = this.dotBias;
this.markLTR = dotLTR;
Highlighter h = component.getHighlighter();
if ((h != null) && (selectionTag != null)) {
h.removeHighlight(selectionTag);
selectionTag = null;
}
}
|
public void install(JTextComponent c) {
component = c;
Document doc = c.getDocument();
dot = mark = 0;
dotLTR = markLTR = true;
dotBias = markBias = Position.Bias.Forward;
if (doc != null) {
doc.addDocumentListener(handler);
}
c.addPropertyChangeListener(handler);
c.addFocusListener(this);
c.addMouseListener(this);
c.addMouseMotionListener(this);
// if the component already has focus, it won't
// be notified.
if (component.hasFocus()) {
focusGained(null);
}
Number ratio = (Number) c.getClientProperty("caretAspectRatio");
if (ratio != null) {
aspectRatio = ratio.floatValue();
} else {
aspectRatio = -1;
}
Integer width = (Integer) c.getClientProperty("caretWidth");
if (width != null) {
caretWidth = width.intValue();
} else {
caretWidth = -1;
}
}
Called when the UI is being installed into the
interface of a JTextComponent. This can be used
to gain access to the model that is being navigated
by the implementation of this interface. Sets the dot
and mark to 0, and establishes document, property change,
focus, mouse, and mouse motion listeners. |
public boolean isActive() {
return active;
}
Determines if the caret is currently active.
This method returns whether or not the Caret
is currently in a blinking state. It does not provide
information as to whether it is currently blinked on or off.
To determine if the caret is currently painted use the
isVisible method. |
boolean isDotLeftToRight() {
return dotLTR;
}
|
boolean isMarkLeftToRight() {
return markLTR;
}
|
boolean isPositionLTR(int position,
Bias bias) {
Document doc = component.getDocument();
if(doc instanceof AbstractDocument ) {
if(bias == Position.Bias.Backward && --position < 0)
position = 0;
return ((AbstractDocument)doc).isLeftToRight(position, position);
}
return true;
}
|
public boolean isSelectionVisible() {
return selectionVisible;
}
Checks whether the current selection is visible. |
public boolean isVisible() {
return visible;
}
Indicates whether or not the caret is currently visible. As the
caret flashes on and off the return value of this will change
between true, when the caret is painted, and false, when the
caret is not painted. isActive indicates whether
or not the caret is in a blinking state, such that it can
be visible, and isVisible indicates whether or not
the caret is actually visible.
Subclasses that wish to render a different flashing caret
should override paint and only paint the caret if this method
returns true. |
public void mouseClicked(MouseEvent e) {
int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e);
if (! e.isConsumed()) {
if (SwingUtilities.isLeftMouseButton(e)) {
// mouse 1 behavior
if(nclicks == 1) {
selectedWordEvent = null;
} else if(nclicks == 2
&& SwingUtilities2.canEventAccessSystemClipboard(e)) {
selectWord(e);
selectedWordEvent = null;
} else if(nclicks == 3
&& SwingUtilities2.canEventAccessSystemClipboard(e)) {
Action a = null;
ActionMap map = getComponent().getActionMap();
if (map != null) {
a = map.get(DefaultEditorKit.selectLineAction);
}
if (a == null) {
if (selectLine == null) {
selectLine = new DefaultEditorKit.SelectLineAction();
}
a = selectLine;
}
a.actionPerformed(new ActionEvent(getComponent(),
ActionEvent.ACTION_PERFORMED, null, e.getWhen(), e.getModifiers()));
}
} else if (SwingUtilities.isMiddleMouseButton(e)) {
// mouse 2 behavior
if (nclicks == 1 && component.isEditable() && component.isEnabled()
&& SwingUtilities2.canEventAccessSystemClipboard(e)) {
// paste system selection, if it exists
JTextComponent c = (JTextComponent) e.getSource();
if (c != null) {
try {
Toolkit tk = c.getToolkit();
Clipboard buffer = tk.getSystemSelection();
if (buffer != null) {
// platform supports system selections, update it.
adjustCaret(e);
TransferHandler th = c.getTransferHandler();
if (th != null) {
Transferable trans = null;
try {
trans = buffer.getContents(null);
} catch (IllegalStateException ise) {
// clipboard was unavailable
UIManager.getLookAndFeel().provideErrorFeedback(c);
}
if (trans != null) {
th.importData(c, trans);
}
}
adjustFocus(true);
}
} catch (HeadlessException he) {
// do nothing... there is no system clipboard
}
}
}
}
}
}
Called when the mouse is clicked. If the click was generated
from button1, a double click selects a word,
and a triple click the current line. |
public void mouseDragged(MouseEvent e) {
if ((! e.isConsumed()) && SwingUtilities.isLeftMouseButton(e)) {
moveCaret(e);
}
}
Moves the caret position
according to the mouse pointer's current
location. This effectively extends the
selection. By default, this is only done
for mouse button 1. |
public void mouseEntered(MouseEvent e) {
}
Called when the mouse enters a region. |
public void mouseExited(MouseEvent e) {
}
Called when the mouse exits a region. |
public void mouseMoved(MouseEvent e) {
}
Called when the mouse is moved. |
public void mousePressed(MouseEvent e) {
int nclicks = SwingUtilities2.getAdjustedClickCount(getComponent(), e);
if (SwingUtilities.isLeftMouseButton(e)) {
if (e.isConsumed()) {
shouldHandleRelease = true;
} else {
shouldHandleRelease = false;
adjustCaretAndFocus(e);
if (nclicks == 2
&& SwingUtilities2.canEventAccessSystemClipboard(e)) {
selectWord(e);
}
}
}
}
If button 1 is pressed, this is implemented to
request focus on the associated text component,
and to set the caret position. If the shift key is held down,
the caret will be moved, potentially resulting in a selection,
otherwise the
caret position will be set to the new location. If the component
is not enabled, there will be no request for focus. |
public void mouseReleased(MouseEvent e) {
if (!e.isConsumed()
&& shouldHandleRelease
&& SwingUtilities.isLeftMouseButton(e)) {
adjustCaretAndFocus(e);
}
}
Called when the mouse is released. |
protected void moveCaret(MouseEvent e) {
Point pt = new Point(e.getX(), e.getY());
Position.Bias[] biasRet = new Position.Bias[1];
int pos = component.getUI().viewToModel(component, pt, biasRet);
if(biasRet[0] == null)
biasRet[0] = Position.Bias.Forward;
if (pos >= 0) {
moveDot(pos, biasRet[0]);
}
}
Tries to move the position of the caret from
the coordinates of a mouse event, using viewToModel().
This will cause a selection if the dot and mark
are different. |
public void moveDot(int dot) {
moveDot(dot, Position.Bias.Forward);
}
Moves the caret position to the specified position,
with a forward bias. |
public void moveDot(int dot,
Bias dotBias) {
if (dotBias == null) {
throw new IllegalArgumentException("null bias");
}
if (! component.isEnabled()) {
// don't allow selection on disabled components.
setDot(dot, dotBias);
return;
}
if (dot != this.dot) {
NavigationFilter filter = component.getNavigationFilter();
if (filter != null) {
filter.moveDot(getFilterBypass(), dot, dotBias);
}
else {
handleMoveDot(dot, dotBias);
}
}
}
Moves the caret position to the specified position, with the
specified bias. |
public void paint(Graphics g) {
if(isVisible()) {
try {
TextUI mapper = component.getUI();
Rectangle r = mapper.modelToView(component, dot, dotBias);
if ((r == null) || ((r.width == 0) && (r.height == 0))) {
return;
}
if (width > 0 && height > 0 &&
!this._contains(r.x, r.y, r.width, r.height)) {
// We seem to have gotten out of sync and no longer
// contain the right location, adjust accordingly.
Rectangle clip = g.getClipBounds();
if (clip != null && !clip.contains(this)) {
// Clip doesn't contain the old location, force it
// to be repainted lest we leave a caret around.
repaint();
}
// This will potentially cause a repaint of something
// we're already repainting, but without changing the
// semantics of damage we can't really get around this.
damage(r);
}
g.setColor(component.getCaretColor());
int paintWidth = getCaretWidth(r.height);
r.x -= paintWidth > > 1;
g.fillRect(r.x, r.y, paintWidth, r.height);
// see if we should paint a flag to indicate the bias
// of the caret.
// PENDING(prinz) this should be done through
// protected methods so that alternative LAF
// will show bidi information.
Document doc = component.getDocument();
if (doc instanceof AbstractDocument) {
Element bidi = ((AbstractDocument)doc).getBidiRootElement();
if ((bidi != null) && (bidi.getElementCount() > 1)) {
// there are multiple directions present.
flagXPoints[0] = r.x + ((dotLTR) ? paintWidth : 0);
flagYPoints[0] = r.y;
flagXPoints[1] = flagXPoints[0];
flagYPoints[1] = flagYPoints[0] + 4;
flagXPoints[2] = flagXPoints[0] + ((dotLTR) ? 4 : -4);
flagYPoints[2] = flagYPoints[0];
g.fillPolygon(flagXPoints, flagYPoints, 3);
}
}
} catch (BadLocationException e) {
// can't render I guess
//System.err.println("Can't render cursor");
}
}
}
Renders the caret as a vertical line. If this is reimplemented
the damage method should also be reimplemented as it assumes the
shape of the caret is a vertical line. Sets the caret color to
the value returned by getCaretColor().
If there are multiple text directions present in the associated
document, a flag indicating the caret bias will be rendered.
This will occur only if the associated document is a subclass
of AbstractDocument and there are multiple bidi levels present
in the bidi element structure (i.e. the text has multiple
directions associated with it). |
protected void positionCaret(MouseEvent e) {
Point pt = new Point(e.getX(), e.getY());
Position.Bias[] biasRet = new Position.Bias[1];
int pos = component.getUI().viewToModel(component, pt, biasRet);
if(biasRet[0] == null)
biasRet[0] = Position.Bias.Forward;
if (pos >= 0) {
setDot(pos, biasRet[0]);
}
}
Tries to set the position of the caret from
the coordinates of a mouse event, using viewToModel(). |
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
Removes a listener that was tracking caret position changes. |
protected final synchronized void repaint() {
if (component != null) {
component.repaint(x, y, width, height);
}
}
Cause the caret to be painted. The repaint
area is the bounding box of the caret (i.e.
the caret rectangle or this).
This method is thread safe, although most Swing methods
are not. Please see
How
to Use Threads for more information. |
void repaintNewCaret() {
if (component != null) {
TextUI mapper = component.getUI();
Document doc = component.getDocument();
if ((mapper != null) && (doc != null)) {
// determine the new location and scroll if
// not visible.
Rectangle newLoc;
try {
newLoc = mapper.modelToView(component, this.dot, this.dotBias);
} catch (BadLocationException e) {
newLoc = null;
}
if (newLoc != null) {
adjustVisibility(newLoc);
// If there is no magic caret position, make one
if (getMagicCaretPosition() == null) {
setMagicCaretPosition(new Point(newLoc.x, newLoc.y));
}
}
// repaint the new position
damage(newLoc);
}
}
}
Repaints the new caret position, with the
assumption that this is happening on the
event thread so that calling modelToView
is safe. |
public void setBlinkRate(int rate) {
if (rate != 0) {
if (flasher == null) {
flasher = new Timer(rate, handler);
}
flasher.setDelay(rate);
} else {
if (flasher != null) {
flasher.stop();
flasher.removeActionListener(handler);
flasher = null;
}
}
}
Sets the caret blink rate. |
public void setDot(int dot) {
setDot(dot, Position.Bias.Forward);
}
Sets the caret position and mark to the specified position,
with a forward bias. This implicitly sets the
selection range to zero. |
public void setDot(int dot,
Bias dotBias) {
if (dotBias == null) {
throw new IllegalArgumentException("null bias");
}
NavigationFilter filter = component.getNavigationFilter();
if (filter != null) {
filter.setDot(getFilterBypass(), dot, dotBias);
}
else {
handleSetDot(dot, dotBias);
}
}
Sets the caret position and mark to the specified position, with the
specified bias. This implicitly sets the selection range
to zero. |
public void setMagicCaretPosition(Point p) {
magicCaretPosition = p;
}
Saves the current caret position. This is used when
caret up/down actions occur, moving between lines
that have uneven end positions. |
public void setSelectionVisible(boolean vis) {
if (vis != selectionVisible) {
selectionVisible = vis;
if (selectionVisible) {
// show
Highlighter h = component.getHighlighter();
if ((dot != mark) && (h != null) && (selectionTag == null)) {
int p0 = Math.min(dot, mark);
int p1 = Math.max(dot, mark);
Highlighter.HighlightPainter p = getSelectionPainter();
try {
selectionTag = h.addHighlight(p0, p1, p);
} catch (BadLocationException bl) {
selectionTag = null;
}
}
} else {
// hide
if (selectionTag != null) {
Highlighter h = component.getHighlighter();
h.removeHighlight(selectionTag);
selectionTag = null;
}
}
}
}
Changes the selection visibility. |
public void setUpdatePolicy(int policy) {
updatePolicy = policy;
}
Sets the caret movement policy on the document updates. Normally
the caret updates its absolute position within the document on
insertions occurred before or at the caret position and
on removals before the caret position. 'Absolute position'
means here the position relative to the start of the document.
For example if
a character is typed within editable text component it is inserted
at the caret position and the caret moves to the next absolute
position within the document due to insertion and if
BACKSPACE is typed then caret decreases its absolute
position due to removal of a character before it. Sometimes
it may be useful to turn off the caret position updates so that
the caret stays at the same absolute position within the
document position regardless of any document updates.
The following update policies are allowed:
NEVER_UPDATE : the caret stays at the same
absolute position in the document regardless of any document
updates, except when document length becomes less than
the current caret position due to removal. In that case caret
position is adjusted to the end of the document.
The caret doesn't try to keep itself visible by scrolling
the associated view when using this policy.
ALWAYS_UPDATE : the caret always tracks document
changes. For regular changes it increases its position
if an insertion occurs before or at its current position,
and decreases position if a removal occurs before
its current position. For undo/redo updates it is always
moved to the position where update occurred. The caret
also tries to keep itself visible by calling
adjustVisibility method.
UPDATE_WHEN_ON_EDT : acts like ALWAYS_UPDATE
if the document updates are performed on the Event Dispatching Thread
and like NEVER_UPDATE if updates are performed on
other thread.
The default property value is UPDATE_WHEN_ON_EDT . |
public void setVisible(boolean e) {
// focus lost notification can come in later after the
// caret has been deinstalled, in which case the component
// will be null.
if (component != null) {
active = e;
TextUI mapper = component.getUI();
if (visible != e) {
visible = e;
// repaint the caret
try {
Rectangle loc = mapper.modelToView(component, dot,dotBias);
damage(loc);
} catch (BadLocationException badloc) {
// hmm... not legally positioned
}
}
}
if (flasher != null) {
if (visible) {
flasher.start();
} else {
flasher.stop();
}
}
}
Sets the caret visibility, and repaints the caret.
It is important to understand the relationship between this method,
isVisible and isActive .
Calling this method with a value of true activates the
caret blinking. Setting it to false turns it completely off.
To determine whether the blinking is active, you should call
isActive . In effect, isActive is an
appropriate corresponding "getter" method for this one.
isVisible can be used to fetch the current
visibility status of the caret, meaning whether or not it is currently
painted. This status will change as the caret blinks on and off.
Here's a list showing the potential return values of both
isActive and isVisible
after calling this method:
setVisible(true) :
- isActive(): true
- isVisible(): true or false depending on whether
or not the caret is blinked on or off
setVisible(false) :
- isActive(): false
- isVisible(): false
|
public String toString() {
String s = "Dot=(" + dot + ", " + dotBias + ")";
s += " Mark=(" + mark + ", " + markBias + ")";
return s;
}
|