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 46 47 48 49 50 51 52 53 54 55 56 |
/* 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); } } |
Add Comment