Whenever a caret changes its position or if text is selected, a caret event is fired by a text component.
The class CaretEvent supports the methods getDot() and getMark() to retrieve the current location and the end position of a text selection, respectively.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class CaretEeventListener {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField();
textField.addCaretListener(new CaretListener() {
public void caretUpdate(CaretEvent e) {
System.out.println(e);
}
});
frame.add(new JScrollPane(textField));
frame.setSize(300, 200);
frame.setVisible(true);
}
}