Bryce Hahn
Bryce Hahn

Reputation: 1773

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. 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?

Upvotes: 1

Views: 3597

Answers (1)

zubergu
zubergu

Reputation: 3706

You assign 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. Add this block of code under you for loop:

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 = "";

cursentence = splitArray[i];

Upvotes: 2

Related Questions