Sujay
Sujay

Reputation: 6783

JTextPane - get start position of a displayed line

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?

Upvotes: 5

Views: 2265

Answers (1)

David Kroukamp
David Kroukamp

Reputation: 36423

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);

Upvotes: 4

Related Questions