Search for cursor position in JTextField

Is there a way to return the character position in a JTextField. I mean, if I have a JTextField with some values ​​in it. For example, the field contains the value ABCDEFJ. The user decides to place the cursor immediately after the 'C' character to enter a new value. Is there any way to get where it enters a new character. In this example, that will return 3.

+6
source share
3 answers

JTextField.getCaretPosition()

JTextField.setCaretPosition(int pos)

+13
source

Try using the CaretListener interface:

 public class A extends JFrame implements CaretListener { //Assume you have a text field. public A() { JTextField field = new JTextField("bla bla"); field.addCaretListener(this); ..... } public void caretUpdate(CaretEvent e) { int index = e.getDot(); ..... } } 

getDot() method of the CaretEvent class returns the desired result, you can assign it to a global variable, which will be used later.

+2
source

Here is your answer:

http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#getCaretPosition%28%29

Use an ActionListener to wait for an action. When the user types, find the position of the carriage.

+1
source

Source: https://habr.com/ru/post/917998/


All Articles