Share the post "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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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; } |
Very helpful. Thank you.
P.S.: if used in for example a CaretListener ensure to run it via SwingUtils.invokeLater otherwise you may get wrong (more precisely a 0) as a result.
@smurffy: yes, you are right. If there is something wrong that does not work here, ensure that any actions is in the SwingUtilities.invokeLater() method
Thank you very much! 😀 you save my day!
But how i change the 0 value if i press ENTER?
I use documentListener.
Thank you very much!
Thank you very much man