How to use Caret to tell which line it is in from JTextPane? (Java)
- by Alex Cheng
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:
Result: 3rd line
Result: 2nd line
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):
--
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.