views:

356

answers:

2

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?

+3  A: 

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
}
ChssPly76
Thanks, I've set your answer to be the accepted one, as you will see from my answer below this is almost exactly what I have done.
Scottm
A: 

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.

Scottm