< Day Day Up > |
Caret events occur when the caret ”the cursor indicating the insertion point ”in a text component moves or when the selection in a text component changes (see Figure 1). The text component's document can initiate caret events when it inserts or removes text, for example. Figure 1. You can see a caret in use in TextComponentDemo ”it's the vertical line at the end of the fourth line.
You can attach a caret listener to an instance of any JTextComponent subclass with the addCaretListener method. Note: An alternate way of detecting caret changes is to attach a listener directly to the caret object itself rather than to the text component that manages the caret. A caret fires change events (not caret events), so you would need to write a change listener rather than a caret listener. Here's the caret event-handling code from an application called TextComponentDemo . //where initialization occurs CaretListenerLabel caretListenerLabel = new CaretListenerLabel("Caret Status"); ... textPane.addActionListener(caretListenerLabel); ... protected class CaretListenerLabel extends JLabel implements CaretListener { ... public void caretUpdate(CaretEvent e) { //Get the location in the text int dot = e.getDot(); int mark = e.getMark(); ... } } Note: The caretUpdate method is not guaranteed to be called in the event-dispatching thread. To use any methods inside of caretUpdate that update the GUI, special handling is required to ensure that they are executed on the event-dispatching thread. You can do this by wrapping the code inside a Runnable and calling SwingUtilities.invokeLater on that Runnable . You can find the full source code for the program and instructions for compiling and running it in Using Text Components (page 60) in Chapter 3. For a discussion about the caret listener aspect of the program see Listening for Caret and Selection Changes (page 74). The Caret Listener APIThe CaretListener interface has just one method (see Table 3), so it has no corresponding adapter class. Table 4 lists the methods in the CaretEvent class. Also see the Caret-Listener API documentation at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/CaretListener.html. The CaretEvent API documentation is online at: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/event/CaretEvent.html. Table 3. The CaretListener Interface
Table 4. The CaretEvent Class
Examples That Use Caret ListenersThe following examples use caret listeners.
|
< Day Day Up > |