5

I've a JTextPane that is used to show a text file. The text appears as follows
Line 1
Line 2
Line 3

What I want to get is the start index of the line where my caret is currently positioned. Is there a simple method in JTextPane that can help me achieve this?

Sujay
  • 6,753
  • 2
  • 30
  • 49

1 Answers1

4

try something like this:

JTextComponent testingArea = new JTextPane();
....
int caretPos = testingArea.getCaretPosition();
int rowNum = (caretPos == 0) ? 1 : 0;
for (int offset = caretPos; offset > 0;) {
    offset = Utilities.getRowStart(textArea, offset) - 1;
    rowNum++;
}
System.out.println("Row: " + rowNum);
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • 1
    Thanks David! This helped me a lot. I didn't have any idea about the `Utilities` class and I found a lot many useful methods in here. +1 for all your help! – Sujay Jul 17 '12 at 16:46