9

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
tadpole
  • 1,209
  • 7
  • 19
  • 28
  • What is the actual use-case here? It is looking like a `JSpinner` (or perhaps an editable `JComboBox`) would be a better component to use. – Andrew Thompson Jun 13 '12 at 16:07
  • This is not a good question because you're asking for a specific code solution rather than how to implement a behavior. The actual solution to your desired behavior may involve a completely different approach. For instance, if you're trying to check a JTextField's input before it is complete, then perhaps what you really want to use is a DocumentFilter. So in the future, please tell us more about the overall problem that you want to solve, and less on how specifically you are trying to solve it. – Hovercraft Full Of Eels Jun 14 '12 at 02:57

3 Answers3

18

JTextField.getCaretPosition()

JTextField.setCaretPosition(int pos)

alaster
  • 3,821
  • 3
  • 24
  • 32
2

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.

Juvanis
  • 25,802
  • 5
  • 69
  • 87
1

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.

Lai Xin Chu
  • 2,462
  • 15
  • 29