How to calclulate the number of lines of text in a div server side in java
I need to calculate the number of lines some saved text will require when displayed.
The text will, ultimately, be displayed in a div 500 pixels wide - the added c开发者_JS百科omplication being that the text can contain \n
('s) so I must factor those into the line number calculation also.
Thanks in advance.
Font font = new Font("Serif", Font.PLAIN, 12);
FontMetrics fontMetrics = getFontMetrics(font);
String text = "a line\nanother line\nsome more line";
String[] lines = text.split("\n");
int lineCount = lines.length;
for(String line : lines) {
int width = fontMetrics.stringWidth(line);
lineCount += (width / 500) > 1 ? (width / 500) - 1 : 0;
}
Change the font settings (font-family, style, size) to your settings.
assumming you have in in some String:
String text = "foo\nbar\baz";
int lines = text.trim().split("\n").length;
If you want to count also empty lines at the end, skip trim().
.
精彩评论