How to use Caret to tell which line it is in from JTextPane? (Java)

Posted by Alex Cheng on Stack Overflow See other posts from Stack Overflow or by Alex Cheng
Published on 2010-05-01T13:20:50Z Indexed on 2010/05/01 13:27 UTC
Read the original article Hit count: 262

Hi all.

Problem: I have CaretListener and DocumentListener listening on a JTextPane.

I need an algorithm that is able to tell which line is the caret at in a JTextPane, here's an illustrative example:

alt text

Result: 3rd line

alt text

Result: 2nd line

alt text

Result: 4th line

and if the algorithm can tell which line the caret is in the JTextPane, it should be fairly easy to substring whatever that is in between the parentheses as the picture (caret is at character m of metadata):

alt text

--

This is how I divide the entire text that I retrieved from the JTextPane into sentences:

String[] lines = textPane.getText().split("\r?\n|\r", -1);

The sentences in the textPane is separated with \n.

Problem is, how can I manipulate the caret to let me know at which position and which line it is in? I know the dot of the caret says at which position it is, but I can't tell which line it is at. Assuming if I know which line the caret is, then I can just do lines[<line number>] and manipulate the string from there.

In Short: How do I use CaretListener and/or DocumentListener to know which line the caret is currently at, and retrieve the line for further string manipulation? Please help. Thanks.

Do let me know if further clarification is needed. Thanks for your time.

© Stack Overflow or respective owner

Related posts about java

Related posts about algorithm