Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
martin Avatar asked Dec 10 '12 19:12

martin


1 Answers

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();
}
like image 171
Reimeus Avatar answered Oct 08 '22 11:10

Reimeus