aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes obtaining mouse pointer position within a document Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "obtaining mouse pointer position within a document" Watch "obtaining mouse pointer position within a document" New topic
Author

obtaining mouse pointer position within a document

kamilla miesak
Ranch Hand

Joined: Mar 06, 2001
Posts: 30
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

Joined: Feb 22, 2001
Posts: 399
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

Joined: Mar 06, 2001
Posts: 30
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

Joined: Mar 06, 2001
Posts: 30
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: obtaining mouse pointer position within a document
 
Similar Threads
help about myeclipse??
To get the coordinates of mouse pointer...
how to get text under current corsor position
Help on JTextField Refreshing Problem
Help on JTextField Refreshing Problem