This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
obtaining mouse pointer position within a document
kamilla miesak
Ranch Hand
Joined: Mar 06, 2001
Posts: 30
posted
0
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
posted
0
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
posted
0
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
posted
0
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