Below code demonstrates how to get current caret position in a JTextField import java.awt.FlowLayout; import javax.swing.JFrame; import...
Below code demonstrates how to get current caret position in a JTextField
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class JTextFieldCaretPosition extends JFrame implements CaretListener{
JTextFieldCaretPosition()
{
this.getContentPane().setLayout(new FlowLayout());
//create new JTextField
JTextField field = new JTextField("JTextField Caret Position Example");
add(field);
//add CaretListener in order to listen for caret position changes
field.addCaretListener(this);
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
//override caretUpdate event to capture caret position changes
public void caretUpdate(CaretEvent e) {
/*
* To get the current position of caret use,
* int getDot()
* method of CaretEvent class.
*/
int position = e.getDot();
//show current position in the status bar of an applet
System.out.println(position);
}
public static void main(String args[]){
new JTextFieldCaretPosition();
}
}
See also: