最后,这是我的解决方案,我知道这不是完美的,因为我可以找到包含大于列宽的单词的字符串的问题......
private int numberOfRows_Calculator(String text, String fontName, int fontSize, int fontStyle, int columnWidth) {
FontRenderContext context = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB).createGraphics().getFontRenderContext();
java.awt.Font font = new Font(fontName, fontStyle, fontSize);
double width;
int numberOfRows = 0;
int breakLineIndex;
boolean continuee = true;
String subtext = text;
String breaklineString = System.getProperty("line.separator");
int breaklineLength = breaklineString.length();
do {
breakLineIndex = subtext.indexOf(breaklineString);
if (breakLineIndex > -1) {
width = font.getStringBounds(subtext.substring(0, breakLineIndex), context).getWidth();
numberOfRows = numberOfRows + (int) (width / columnWidth) + 1;
subtext = subtext.substring(breakLineIndex + breaklineLength, subtext.length());
} else {
width = font.getStringBounds(subtext, context).getWidth();
numberOfRows = numberOfRows + (int) (width / columnWidth) + 1;
continuee = false;
}
} while (continuee);
return numberOfRows;
}