如何得到光标位置

joejoe1991 2007-07-21 10:52:55
一个文本框和一个JLable
lable显示当前光标在文本框的第几行

请问应该怎么得到当前光标的位置?
谢谢回答!
...全文
440 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
joejoe1991 2007-07-24
  • 打赏
  • 举报
回复
谢谢
boby 2007-07-24
  • 打赏
  • 举报
回复
返回行号:
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做为参数给进去,就能得到值了
joejoe1991 2007-07-24
  • 打赏
  • 举报
回复
ukeychen 2007-07-23
  • 打赏
  • 举报
回复
ding
joejoe1991 2007-07-23
  • 打赏
  • 举报
回复
汗 我不是要得到mouse的坐标
我是要得到光标现在的位置 比如下面是文本框的内容:
(|)就是光标的位置 那label就应该显示1,5(第一行第五个字符后面)
12354(|)543132
212445
3243132
joejoe1991 2007-07-22
  • 打赏
  • 举报
回复
getCaretPosition() 这个方法好像和我的需求不太一样啊。 这个方法是得到当前光标在第几个字符后面 而我要的是得到当前光标在第几行 在那一行的第几个字符后面
lanseliuying 2007-07-22
  • 打赏
  • 举报
回复
添加鼠标事件
class ML extend MouseAdapter{
public void mousePressed(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
Point p = me.getPoint();//这个和上面的位置是相同的
}
}
试一下
lanseliuying 2007-07-21
  • 打赏
  • 举报
回复
TextField tf=new TextField();
int i=tf.getCaretPosition();//i既是text中的位置
joejoe1991 2007-07-21
  • 打赏
  • 举报
回复

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧