Is there a way of "extracting" the number of lines from a filled with text jtextpane? If there is, does it work if some of the lines are due to text wrapping?
Asked
Active
Viewed 7,181 times
4 Answers
15
You can use Utilities.getRowStart
to determine the 'start' of the line for a JTextPane
giving you a resulting lineCount
. This will also work when the lines are wrapped.
int totalCharacters = textPane.getText().length();
int lineCount = (totalCharacters == 0) ? 1 : 0;
try {
int offset = totalCharacters;
while (offset > 0) {
offset = Utilities.getRowStart(textPane, offset) - 1;
lineCount++;
}
} catch (BadLocationException e) {
e.printStackTrace();
}

Reimeus
- 158,255
- 15
- 216
- 276
-
Just a note: "This will also work when the lines are wrapped." means that if a line gets wrapped automatically, the resulting number will be increased by the amount of wraps. So, when you eg. want to display line numbers, you have to check if a line really is a line or just displayed as a line because of automatic wrapping. – Bowi Jun 06 '17 at 11:14
5
If you define a "line" as how many \n
characters are there in a JTextPane text, then you could use:
JTextPane p = yourJTextPane;
System.out.println(p.getText().split("\n").length);

Pablo Santa Cruz
- 176,835
- 32
- 241
- 292
-
Thanks, though I already tried that. The problem is that when the jtextPane wraps a line, it seems that it doesn't put a "\n"? I can't really undestand why. – martin Dec 10 '12 at 19:35
-
No, it doesn't. If that's what you need, you can't use my answer. – Pablo Santa Cruz Dec 10 '12 at 19:45
0
To jump to line that was selected, I used this code:
int rowSel = Integer.parseInt(tfGoLine.getText());
int rowGo = 0;
int lineCount = 0;
int totalCharacters = rowSel <= 1 ? 0 : text.getText().length();
try {
int last = -1;
for (int count = 0; count < totalCharacters; count++) {
int offset = Utilities.getRowStart(text, count);
if (last != offset) {
last = offset;
lineCount++;
rowGo = offset;
if (lineCount == rowSel) {
break;
}
}
}
} catch (BadLocationException e) {
}
text.getCaret().setDot(rowGo);
text.requestFocus();

Marcus Becker
- 352
- 4
- 11
0
int rowCount =txtPane.getDocument().getDefaultRootElement().getElementCount();

Zoe
- 27,060
- 21
- 118
- 148