Finding the cursor text position in JTextField

蹲街弑〆低调 提交于 2019-12-23 07:58:08

问题


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.


回答1:


JTextField.getCaretPosition()

JTextField.setCaretPosition(int pos)




回答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.




回答3:


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.



来源:https://stackoverflow.com/questions/11018837/finding-the-cursor-text-position-in-jtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!