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

I am currently trying to solve a problem when I need to find a position in a piece of text in JEditorPane, based on a mouse click.

Basically, when a user right-clicks on a word, I need to find out what the word is. To do this, I need to find out what position in the text the user clicked. I know that I can easily get the mouse position from the MouseEvent, which is passed to the mousePressed method, and I am told that you can convert this to get the index of the character in a piece of text - however, I cannot figure out how to do this.

I tried the viewToModel () method on JEditorPane, but that returns me the wrong position in the text, so either I use it incorrectly or it doesn't work that way.

Any ideas?

+6
java swing cursor jeditorpane
source share
2 answers

Calling viewToModel() is the right 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 } 
+9
source share

I solved this problem myself. It turns out that viewToModel () is exactly what I have to use here, the problem was that I was passing at the wrong point.

From MouseEvent, I used the getLocationOnScreen () method to determine the point when, in fact, I had to use the getPoint () method.

Thanks to everyone who read this question.

0
source share

All Articles