当前位置: 代码迷 >> J2SE >> 怎么得到光标位置
  详细解决方案

怎么得到光标位置

热度:44   发布时间:2016-04-24 14:24:51.0
如何得到光标位置
一个文本框和一个JLable  
lable显示当前光标在文本框的第几行

请问应该怎么得到当前光标的位置?
谢谢回答!

------解决方案--------------------
TextField tf=new TextField();
int i=tf.getCaretPosition();//i既是text中的位置
------解决方案--------------------
返回行号:
public static int getLineAtCaret(JTextComponent component) {
int caretPosition = component.getCaretPosition();
Element root = component.getDocument().getDefaultRootElement();
return root.getElementIndex( caretPosition ) + 1;
}

返回列号:
public static int getCaretColumnPosition(JTextComponent component) {
int offset = component.getCaretPosition();
int column;
try {
column = offset - Utilities.getRowStart(component, offset);
} catch (BadLocationException e) {
column = -1;
}
return column;
}

把你的JTextArea做为参数给进去,就能得到值了
  相关解决方案