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!
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();
}