0

I have a JTextPane and using a MouseAdapter I need to get the position ofthe char that is clicked on. Using viewToModel does return the wanted position when I click directly over chars, however, it returns the position of the last char in the row when I click in the empty area of the JTextPane.

Does anyone know how I can avoid getting the position of the last char when I don't click on chars?

Hers's the code that gets the position:

public void mouseClicked(MouseEvent e) {
    JTextPane editor = (JTextPane) e.getSource();
    Point pt = new Point(e.getX(), e.getY());
    int pos = editor.viewToModel(pt);
}
Igor
  • 1,532
  • 4
  • 23
  • 44
  • 1
    don't understand, you can to check (avoid getting the position of the last char when I don't click on chars?) the Caret possition – mKorbel Dec 31 '12 at 14:43
  • @mKorbel Yes, the Caret is positioned at the position that viewToModel returns. Obviously I don't need that when I click off text. – Igor Dec 31 '12 at 17:09

1 Answers1

1

What result do you expect when click on empty area? Actually it returns closest position to the clicked point.

You can get the position from viewToModel() and use modelToView() passing the obtained offset. Then just compare returned rectangle with the clicked point.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • @Igor whats Rectangle, only selection can returns that, really post an SSCCE about that, to avoiding missinterpretations ...... – mKorbel Dec 31 '12 at 17:37
  • That's OK, I found another workaound to this. Since I'm using this to recognise hyperlinks I used `Element el = doc.getCharacterElement(pos);` to get the element and check if it has the blue foreground attribute. Thanks anyway guys. – Igor Dec 31 '12 at 17:44