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

时间:2023-01-27 20:05:49

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.

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

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.

基本上,当用户右键单击一个单词时,我需要找出单词是什么。为此,我需要找出用户点击的文本中的哪个位置。我知道我可以轻松地从MouseEvent获取鼠标位置,该鼠标位置传递给mousePressed方法,我被告知你可以转换它来获取文本中的字符索引 - 但是我无法弄清楚怎么做这个。

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.

我已经尝试过JEditorPane上的viewToModel()方法但是这会让我回到文本中错误的位置,所以要么我使用它错了要么它不能以这种方式工作。

Any ideas?

2 个解决方案

#1


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

调用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
}

#2


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.

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

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.

从MouseEvent,我使用getLocationOnScreen()方法计算出实际上我应该使用getPoint()方法的点。

Thanks to anyone who read this question.

感谢任何阅读此问题的人。

#1


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

调用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
}

#2


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.

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

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.

从MouseEvent,我使用getLocationOnScreen()方法计算出实际上我应该使用getPoint()方法的点。

Thanks to anyone who read this question.

感谢任何阅读此问题的人。