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;
}

Word Count In Java

This custom made method of by Parth Gallen counts the number of words found in a String object. This method detects new lines to count them as another word whenever it encounters one. To use the method, simply call it like in the code below:

System.out.println(countWords(STRING_OBJECT));

Here is the code for counting the words found in a String.

public static int countWords(String s) {
    int counter = 0;
    boolean word = false;
    int endOfLine = s.length()-1;
 
    for (int i =0; i < s.length(); i++) {
        //if the ;char is letter, word = true.
        if (Character.isLetter(s.charAt(i)) == true && i != endOfLine) {
            word = true;
        //if charisnt letter and there have been letters before (word == true), counter goes up.
        } else if (Character.isLetter(s.charAt(i)) == false && word == true) {
            counter++;
            word= false;
        //last wordof String, if it doesnt end with nonLetter it wouldnt count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            counter++;
        }
    }
    return counter;
}
Related Posts Plugin for WordPress, Blogger...