Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages

How to Write a Caret Listener


Note: This section assumes that you're familiar with the AWT event listener scheme. If you aren't, you can read about it in The 1.1 AWT Event Model(in the Creating a User Interface trail).
Caret events occur when the caret in a text component moves or when the selection in a text component changes. You can attach a caret listener to an instance of any JTextComponent subclass with the addCaretListener method.

If your program has a custom caret, you might find it more convenient to attach a listener to the caret object rather than to the text component for which it is a caret. A caret generates change events rather than caret events, so you would need to write a change listener rather than a caret listener. See [PENDING] for information about change listeners.

Caret Event Methods

The CaretListener interface has just one method, so it has no corresponding adapter class. Here's the method:
void caretUpdate(CaretEvent)
Called when the caret in the listened-to component moves or when the selection in the listened-to component changes.

Examples of Handling Caret Events

The example described in How to Use Text Components has a caret listener that displays caret and selection status. Refer to the section titled Listening for Caret and Selection Changes for the related code and a description.

The CaretEvent Class

The caretUpdate method has a single parameter: a CaretEvent(in the API reference documentation) object. To get the text component that generated the event, use the getSource method which CaretEvent inherits from EventObject(in the API reference documentation).

The CaretEvent class defines two useful methods:

int getDot()
Returns the current location of the caret. If text is selected, the caret marks one end of the selection.
int getMark()
Returns the other end of the selection. If nothing is selected, the value returned by this method is equal to the value returned by getDot


Previous | Next | Trail Map | Creating a User Interface | Using the JFC/Swing Packages