[英]Java split string into multiple lines
我正在做一個帶有文本框的小游戲。 文本框將繪制一個字符串,該字符串將分成多行以適合該文本框。 我在“分成多行”部分遇到了一些麻煩。
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)
是我編寫的一種方法int getStringWidth(String sentence, Font font)
該方法返回以像素為單位的字符串寬度。 此方法有效; 這不是問題。
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());
}
輸出應如下所示:
Line 0 - This is a long message to make sure
Line 1 - that the line separation works.
Line 2 - null
Line 3 - null
但是只會打印出第一行,最后3行只是null。 因此由於某種原因, for
循環在完成第一行后就中斷了。
這里發生了什么?
您分配line[curline] = cursentence;
僅當您的當前行已滿時。 但是您不會在for循環結束后進行分配,這意味着用完所有單詞時剩下的會丟失。 在您for
循環下面添加以下代碼塊:
if (!"".equals(cursentence)) {
line[curline] = cursentence;
}
正如@rodrigoap所說,您還需要以不適合第一行的單詞開始新行,該單詞不再插入cursentence = "";
而是插入else
塊cursentence = "";
cursentence = splitArray[i];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.