1

Hi I am making a quiz application. I would like to draw the question on the screen. If the question is too long, I place a \n in the string so it should go to a newline. But g.drawstring doesn't recognize this \n.

This is my code :

/* Draw the question*/
StringBuilder sb = new StringBuilder($question.getQuestion());

int x = 0;
while ((x = sb.indexOf(" ", x + 20)) != -1){
    sb.replace(x, x + 1, "\n");
}

System.out.println(sb.toString());

g.drawString(sb.toString(), 125, 120);

The output I get in my console is :
Which engineer made the
Eiffel Tower in Paris?

So the code is working, how can I let g.drawstring handle this string? Because it draws something like this : Which engineer made theEiffel Tower in Paris. So It doesn't read the \n and just pastes the words together.

Thanks!

user3485470
  • 121
  • 5
  • 11
  • I think this is what you are looking for [\n in drawstring](http://stackoverflow.com/questions/4413132/problems-with-newline-in-graphics2d-drawstring) – Sarwar Jun 03 '14 at 10:57

1 Answers1

1

you could use drawString for every line

Graphics2D g2d ;

String s = "hello\nworld";
int x = 0, y = 0;
String[] lines = s.split("\\n");
for(int i=0,l = lines.length;i<l;i++) {
    String curLine = lines[i].trim();
    FontMetrics fm = g2d.getFontMetrics();
    Rectangle2D r = fm.getStringBounds(curLine, g2d);
    g2d.drawString(curLine, x, y);
    y += r.getHeight() + fm.getAscent();    
}
Zahlii
  • 818
  • 1
  • 7
  • 17