简体   繁体   中英

How to convert from a mouse position to a character position in a JEditorPane in Java Swing

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?

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM