Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
Scottm Avatar asked Jul 24 '09 21:07

Scottm


1 Answers

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
}
like image 129
ChssPly76 Avatar answered Oct 06 '22 00:10

ChssPly76