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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With