This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

obtaining mouse pointer position within a document

 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I'm trying to find out how to obtain mouse pointer position within a document and then translate it to line and character number. This functionality exists in many applications, i.e. JBuilder or TextPad.
I've been searching Java API for a solution, but I haven't found one yet.
Any ideas?
Thanks!
Kamilla
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume that by mouse position, you mean the little vertical bar left when you click on a text componenent with the mouse, which is called the caret. It's location is called the dot.
Assuming you are working with a subclass of JTextComponent, try
int offset= textComponent.getCaret().getDot();
That gives you the character offset from the beginning of the document to the dot.
Then, if you are working with a JTextArea, you can use
int line = textArea.getLineOfOffset(offset);
If not using JTextArea, but PlainDocument or another Document organized the same way, you might try
int line = component.getDocument().getDefaultRootElement().getElementIndex(offset);
As for StyledDocuments, I don't know, and don't have my books here.
 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much!
JTextComponent was one of the classes I looked at, but I had no idea that the term "caret" was what I should have been looking for.
Thanks again!
 
kamilla miesak
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have another question:
is there a way to get an offset within a specific line as oppose to an offset for an entire JTextArea. When I do:
int offset= JTextArea.getCaret().getDot();
int line = JTextArea.getLineOfOffset(offset);
I do get correct line numbers, but the offset of the last character from a previous line is being carried over to the next line and calculated continuosly for the entire document.
I've tried couple of ways to calculate it separately, but nothing worked so far.
Thank you
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic