Get Line Count Of JTextArea Including Word Wrap Lines

After almost a work day’s worth of searching, I was able to find a solution to my dilemna. While JTextArea has a getLineCount() method to return the number of lines, I wanted a way to also detect wrapped lines since I wanted to set my component a fixed height if the maximum height limit is reached.

This method by user Jörg in the Java forum did the trick.

public static int getLineCountAsSeen(JTextComponent txtComp) {
	Font font = txtComp.getFont();
    FontMetrics fontMetrics = txtComp.getFontMetrics(font);
    int fontHeight = fontMetrics.getHeight();
    int lineCount;
    try {
    	int height = txtComp.modelToView(txtComp.getDocument().getEndPosition().getOffset() - 1).y;
    	lineCount = height / fontHeight + 1;
    } catch (Exception e) { 
    	lineCount = 0;
    }      
    return lineCount;
}
Related Posts Plugin for WordPress, Blogger...