I am making a little game which has a text box. The text box will draw a string which will separate into multiple lines to fit into the text box. I am having a little bit of trouble with the "separating into multiple lines" part.
String[] line = new String[4];
int boxWidth = 200;
String MESSAGE = "This is a long message to make sure that the line separation works.";
String[] splitArray = null;
try {
splitArray = MESSAGE.split("\\s+"); //split the words of the sentence into an array
} catch (PatternSyntaxException e) {
CrashDumping.DumpCrash(e);
}
String cursentence = "";
int curleng = 0;
int curline = 0;
for (int i = 0; i < splitArray.length; i++) {
if (curleng + m.getStringWidth(splitArray[i], r.font1) <= boxWidth) {
curleng += m.getStringWidth(splitArray[i], r.font1);
cursentence += splitArray[i]; cursentence += " ";
} else {
line[curline] = cursentence;
cursentence = "";
curline++;
curleng = 0;
}
}
for (int i = 0; i < line.length; i++) {
System.out.println("Line " + i + " - " + line[i]);
}
int getStringWidth(String sentence, Font font)
is a method I wrote which return the string width in pixels. This method works; it is not the problem.
public int getStringWidth(String text, Font font) {
AffineTransform affinetransform = new AffineTransform();
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
return (int)(font.getStringBounds(text, frc).getWidth());
}
The output should look something like this:
Line 0 - This is a long message to make sure
Line 1 - that the line separation works.
Line 2 - null
Line 3 - null
But will only print out the first line, the last 3 are just null. So for some reason the for
loop is breaking after finishing the first line.
What is going on here?