如何在 Java Swing 的 JEditorPane 中将鼠标位置转换为字符位置
我目前正在尝试解决一个问题,我需要根据鼠标单击的位置找到 JEditorPane 中一段文本的位置。
基本上,当用户右键单击一个单词时,我需要找出该单词是什么。 为此,我需要找出用户单击了文本中的哪个位置。 我知道我可以轻松地从传递到 mousePressed 方法的 MouseEvent 中获取鼠标位置,并且我被告知您可以将其转换以获取文本片段中的字符索引 - 但是我不知道该怎么做这。
我已经在 JEditorPane 上尝试了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
viewToModel()
是执行此操作的正确方法:Invoking
viewToModel()
is the correct way to do this:我已经自己解决了这个问题。 事实证明 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.