[solved] Breaking lines on drawString()

I’m going to make a briefing state that telling story with some words running (like typewritter) in screen. Some kind like this

NOTE: you’ll notice I quote an example from RE3 ::slight_smile:

However, it seems that break line \n doesnt work on g.drawString() method. The full length text went out the screen. My current approach is create N number of string in array for every number of line.


public void update(long delta){
		d += delta;
		if (d > 50 && !finish){
			if (!halfFinish){
				sb1.append(TEXT[level][0].charAt(textCount));
				textCount++;
				if (textCount == TEXT[level][0].length()){
					textCount = 0;
					halfFinish = true;
				}
				d = 0;
			}else{
				sb2.append(TEXT[level][1].charAt(textCount));
				textCount++;
				if (textCount == TEXT[level][1].length())
					finish = true;
				d = 0;
			}
		}
	}

	public void draw(Graphics2D g){
		g.setColor(Color.black);
		g.drawString(sb1.toString(),50,100);
		g.drawString(sb2.toString(),50,200);
	}

This is not good and I want to know your better approach for this problem. Thanks 8)

At some point you’ll need to call drawString for each line.

If I had to do this task, I would write some kind of code that calculates where the line breaks should be (see TextArea.java or JTextArea.java). If the string already has them then your task is easy.

For each line, call drawString but do it in a loop instead and use FontMetrics.getHeight to calculate how far apart vertically each line should be.

I approve !

Well:


public static void drawStrings(String ln[], int x, int y, Graphics g)
    {
        int h = g.getFont().getLineHeight();
        for (int i=0; i<ln.length; i++)
        {
            g.drawString(ln[i], x, y+(h*i) + h);
        }
    }

this is my usual routine. Now… you can make it, so that null Strings will be ignored. Or you could even make it so that the method can also get one string which has \n’s and then splits this and passes it to this method, and so on.
obviously you can also add a padding parameter and stuff.

@Cero
Hehe so RE fans too huh? :slight_smile:
Your method give me idea how to solve this. I’ll let the method to split the string inside and update Y value. Ofc it only work in same distance between lines. Thanks.