Get Current Caret Position in JTextField Example
- /*
- Get Current Caret Position in JTextField Example
- This java example shows how to get current position of caret in JTextField
- using Java Swing JTextField class.
- */
- import java.awt.FlowLayout;
- import javax.swing.JApplet;
- import javax.swing.JTextField;
- import javax.swing.event.CaretEvent;
- import javax.swing.event.CaretListener;
- /*
- <applet code="GetCaretPositionInJTextFieldExample" width=200 height=200>
- </applet>
- */
- /*
- * Implement CaretListener in order to listen for caret position
- * change event.
- */
- public class GetCaretPositionInJTextFieldExample extends JApplet implements CaretListener{
- public void init(){
- //set flow layout for the applet
- 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);
- }
- //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
- getAppletContext().showStatus("Caret Position :" + position);
- }
- }



