如何在 Java Swing 的 JEditorPane 中将鼠标位置转换为字符位置

发布于 2024-07-29 13:27:34 字数 325 浏览 5 评论 0原文

我目前正在尝试解决一个问题,我需要根据鼠标单击的位置找到 JEditorPane 中一段文本的位置。

基本上,当用户右键单击一个单词时,我需要找出该单词是什么。 为此,我需要找出用户单击了文本中的哪个位置。 我知道我可以轻松地从传递到 mousePressed 方法的 MouseEvent 中获取鼠标位置,并且我被告知您可以将其转换以获取文本片段中的字符索引 - 但是我不知道该怎么做这。

我已经在 J​​EditorPane 上尝试了 viewToModel() 方法,但是这给了我在文本中的错误位置,所以要么我使用错误,要么它无法以这种方式工作。

有任何想法吗?

I'm currently trying to solve a problem where I need to find the position in a piece of text in a JEditorPane based on where the mouse was clicked.

Basically, when the user right-clicks over a word I need to find out what the word is. To do this I need to find out which position in the text the user has clicked on. I know I can easily get the mouse position from the MouseEvent which is passed into the mousePressed method, and I am told that you can convert this to get the character index in the piece of text - however I can't figure out how to do this.

I have tried the viewToModel() method on JEditorPane however this is giving me back the wrong position in the text so either I'm using it wrong or it doesn't work in this way.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

煮酒 2024-08-05 13:27:34

调用 viewToModel() 是执行此操作的正确方法:

public void mouseClicked(MouseEvent e) {
    JEditorPane editor = (JEditorPane) e.getSource();
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
    // whatever you need to do here
}

Invoking viewToModel() is the correct way to do this:

public void mouseClicked(MouseEvent e) {
    JEditorPane editor = (JEditorPane) e.getSource();
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
    // whatever you need to do here
}
鲜肉鲜肉永远不皱 2024-08-05 13:27:34

我已经自己解决了这个问题。 事实证明 viewToModel() 正是我应该在这里使用的,问题是我传递了错误的 Point 给它。

在 MouseEvent 中,我使用 getLocationOnScreen() 方法来计算出这一点,而实际上我应该使用 getPoint() 方法。

感谢任何读过这个问题的人。

I've solved this problem on my own. It turns out viewToModel() is exactly what I should be using here, the problem was that I was passing in the wrong Point to it.

From the MouseEvent, I was using the getLocationOnScreen() method to work out the point when in fact I should have been using the getPoint() method.

Thanks to anyone who read this question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文