Search code examples
javaswingjtextpaneword-wrap

How to get the number of lines from a jtextpane


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?


Solution

  • 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();
    }