Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with newline in Graphics2D.drawString

g2 is an instance of the class Graphics2D. I'd like to be able to draw multi-line text, but that requires a newline character. The following code renders in one line.

String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);
like image 516
pkinsky Avatar asked Dec 10 '10 20:12

pkinsky


2 Answers

The drawString method does not handle new-lines.

You'll have to split the string on new-line characters yourself and draw the lines one by one with a proper vertical offset:

void drawString(Graphics g, String text, int x, int y) {
    for (String line : text.split("\n"))
        g.drawString(line, x, y += g.getFontMetrics().getHeight());
}

Here is a complete example to give you the idea:

import java.awt.*;

public class TestComponent extends JPanel {

    private void drawString(Graphics g, String text, int x, int y) {
        for (String line : text.split("\n"))
            g.drawString(line, x, y += g.getFontMetrics().getHeight());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawString(g, "hello\nworld", 20, 20);
        g.setFont(g.getFont().deriveFont(20f));
        drawString(g, "part1\npart2", 120, 120);
    }

    public static void main(String s[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new TestComponent());
        f.setSize(220, 220);
        f.setVisible(true);
    }
}

which gives the following result:

enter image description here

like image 117
aioobe Avatar answered Nov 05 '22 02:11

aioobe


I just made a method to draw long text spliting automaticaly by giving the line width.

public static void drawStringMultiLine(Graphics2D g, String text, int lineWidth, int x, int y) {
    FontMetrics m = g.getFontMetrics();
    if(m.stringWidth(text) < lineWidth) {
        g.drawString(text, x, y);
    } else {
        String[] words = text.split(" ");
        String currentLine = words[0];
        for(int i = 1; i < words.length; i++) {
            if(m.stringWidth(currentLine+words[i]) < lineWidth) {
                currentLine += " "+words[i];
            } else {
                g.drawString(currentLine, x, y);
                y += m.getHeight();
                currentLine = words[i];
            }
        }
        if(currentLine.trim().length() > 0) {
            g.drawString(currentLine, x, y);
        }
    }
}
like image 13
Ivan De Sousa Paz Avatar answered Nov 05 '22 02:11

Ivan De Sousa Paz