java 在 JTextField 中查找光标文本位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11018837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the cursor text position in JTextField
提问by tadpole
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.
是否有返回字符在 JTextField 中的位置的方法。我的意思是,如果我有一个带有一些值的 JTextField。例如,该字段包含值 ABCDEFJ。用户决定将光标放在字符“C”之后以输入新值。有没有办法获得他进入新角色的位置。在这个例子中,这将返回一个 3。
回答by alaster
JTextField.getCaretPosition()
JTextField.getCaretPosition()
JTextField.setCaretPosition(int pos)
JTextField.setCaretPosition(int pos)
回答by Juvanis
Try getting use of CaretListener
interface:
尝试使用CaretListener
接口:
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.
getDot()
CaretEvent
类的方法返回您想要的结果,您可以将其分配给全局变量以供以后使用。
回答by Lai Xin Chu
Here's your answer:
这是你的答案:
http://docs.oracle.com/javase/6/docs/api/javax/swing/text/JTextComponent.html#getCaretPosition%28%29
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.
使用 ActionListener 等待操作。当用户键入内容时,找到插入符号位置。