Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the cursor text position in JTextField

Is there a method to return the position of the character in the JTextField. What I mean by that is if I have a JTextField with some values in it. For example, the field contains value ABCDEFJ. The user decides to put the cursor right after the character 'C' to enter a new value. Is there a method to get position where he enters the new character. In this example, that would return a 3.

like image 279
tadpole Avatar asked Jun 13 '12 15:06

tadpole


3 Answers

JTextField.getCaretPosition()

JTextField.setCaretPosition(int pos)

like image 52
alaster Avatar answered Oct 24 '22 23:10

alaster


Try getting use of 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 CaretEvent class returns the result you desire, you can assign it to a global variable to use later on.

like image 32
Juvanis Avatar answered Oct 24 '22 23:10

Juvanis


Here's 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 something, find the caret position.

like image 1
Lai Xin Chu Avatar answered Oct 25 '22 01:10

Lai Xin Chu