Java将字符串拆分为多行

时间:2015-03-22 23:24:14

标签: java split

我正在制作一个带有文本框的小游戏。文本框将绘制一个字符串,该字符串将分成多行以适合文本框。我在“分成多行”部分遇到了一些麻烦。

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)是我写的一个方法,它返回字符串宽度(以像素为单位)。这种方法有效;这不是问题。

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

但是只打印出第一行,后三行只是空。因此,出于某种原因,for循环在完成第一行后就会中断。

这里发生了什么?

1 个答案:

答案 0 :(得分:2)

仅在当前行已满时指定line[curline] = cursentence;。但是你在for循环结束后没有完成任务,这意味着当你用完单词时你的余数会丢失。 在for循环:

下添加此代码块
if (!"".equals(cursentence)) {
    line[curline] = cursentence;
}

正如@rodrigoap所说,你还需要用第一行中不适合的单词开始你的新行,这个单词进入else块而不是cursentence = "";

cursentence = splitArray[i];