简体   繁体   English

Java将字符串分成多行

[英]Java split string into multiple lines

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. int getStringWidth(String sentence, Font font)是我编写的一种方法int getStringWidth(String sentence, Font font)该方法返回以像素为单位的字符串宽度。 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. 但是只会打印出第一行,最后3行只是null。 So for some reason the for loop is breaking after finishing the first line. 因此由于某种原因, for循环在完成第一行后就中断了。

What is going on here? 这里发生了什么?

You assign line[curline] = cursentence; 您分配line[curline] = cursentence; only when your current line is full. 仅当您的当前行已满时。 But you don't make assignment after the for loops finishes, meaning your remainder when you run out of words gets lost. 但是您不会在for循环结束后进行分配,这意味着用完所有单词时剩下的会丢失。 Add this block of code under you for loop: 在您for循环下面添加以下代码块:

if (!"".equals(cursentence)) {
    line[curline] = cursentence;
}

As @rodrigoap said, you also need to start your new line with the word that didn't fit in the first line, which goeas into else block instead of cursentence = ""; 正如@rodrigoap所说,您还需要以不适合第一行的单词开始新行,该单词不再插入cursentence = "";而是插入elsecursentence = "";

cursentence = splitArray[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM