How to convert mouse position to character position in jeditorpane in Java Swing

I'm trying to solve a problem. I need to find a position in a text in jeditor pane according to the position of clicking the mouse

Basically, when the user right clicks a word, I need to find out what the word is To do this, I need to find out where the user clicks in the text I know I can easily get the mouse position from mouseevent, which is passed to the mousePressed method. I'm told you can convert it to get the character index in the text - but I can't figure out how to do this

I've tried the viewtomodel () method on jeditorpane, but it will get me back to the wrong place in the text, so either I used it wrong or it can't work this way

Any ideas?

Solution

Calling 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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>