How to get the number of lines from a jtextpane
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();
}
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);