Java Reference
In-Depth Information
The blinkRate is the millisecond delay between the flashes of the caret. The dot property
is the current position within the text component of the cursor. To move the cursor to another
position so that some text will be highlighted, add a call to the moveDot(int newPosition)
method. This sets the mark property to the old dot position and sets the new dot setting to the
new position.
The magicCaretPosition property deals with moving up and down lines of different
lengths. For example, suppose the following three lines of text were on your screen:
Friz Freleng
Mel Blanc
What's up Doc?
Now suppose that the current cursor position is between the n and g on the first line. If you
pressed the down arrow twice, you would want the cursor to stay at the same horizontal posi-
tion, instead of moving to the end of the shorter second line. It's the magicCursorPosition
property that retains this information, so that the cursor ends up being between the D and the
o in the third line. Without the magic position retained, the cursor would fall in between the p
and the word space of the last line.
One useful instance of using the caret is to find the current screen location in response to
a keystroke. That way, you can pop up a menu at the current cursor position. This would be
similar to the Code Insights option in JBuilder or IntelliSense in Visual Studio, in which the
tool helps you complete method calls by popping up a menu of methods. Given the current
dot location in the model, map it to the position in the view with the public Rectangle
modelToView(int position) method of JTextComponent (which can throw a BadLocationException ).
Then use the Rectangle returned as the location to pop up the menu, as shown in Figure 15-10.
Figure 15-10. Using the Caret to determine a pop-up location
The program in Listing 15-9 will show a JPopupMenu at the location where the period (.) key
is pressed in the text field.
Listing 15-9. Mapping Caret Location to Pop-Up Position
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.plaf.*;
import java.awt.*;
import java.awt.event.*;
 
Search WWH ::




Custom Search