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

2

7

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?

Practically answered 24/7, 2009 at 21:58 Comment(0)
H
9

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
}
Harry answered 24/7, 2009 at 22:5 Comment(3)
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.Practically
@Harry Can this somehow be used for a JTable instead?Ammadas
The method viewToModel() is already provided by the more general class JTextComponent. For a JTable there are other methods that would first return the Cell, and then one would need to call an appropriate method depending on the Cell renderer/editor.Olmsted
P
0

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.

Practically answered 24/7, 2009 at 22:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.