1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
//This listens for and reports caret movements.
protected class CaretListenerLabel extends JLabel
implements CaretListener {
public CaretListenerLabel(String label) {
super(label);
}
//Might not be invoked from the event dispatching thread.
public void caretUpdate(CaretEvent e) {
displaySelectionInfo(e.getDot(), e.getMark());
}
//This method can be invoked from any thread. It
//invokes the setText and modelToView methods, which
//must run in the event dispatching thread. We use
//invokeLater to schedule the code for execution
//in the event dispatching thread.
protected void displaySelectionInfo(final int dot,
final int mark) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (dot == mark) { // no selection
try {
Rectangle caretCoords = textPane.modelToView(dot);
//Convert it to view coordinates.
setText("caret: text position: " + dot
+ ", view location = ["
+ caretCoords.x + ", "
+ caretCoords.y + "]"
+ newline);
} catch (BadLocationException ble) {
setText("caret: text position: " + dot + newline);
}
} else if (dot < mark) {
setText("selection from: " + dot
+ " to " + mark + newline);
} else {
setText("selection from: " + mark
+ " to " + dot + newline);
}
}
});
}
} |