Break lines in g.drawString in Java SE

ArMEd picture ArMEd · Dec 30, 2011 · Viewed 8.6k times · Source

This is exactly what I'm trying to do:

Graphics2D g2 = (Graphics2D) g;
g2.setFont(new Font("Serif", Font.PLAIN, 5));
g2.setPaint(Color.black);
g2.drawString("Line 1\nLine 2", x, y);

That line prints like this:

Line1Line2

I want it like this:

Line1
Line2

How can I do this in drawString ?

As well as how can I do a tab space for a line??

Answer

Rupok picture Rupok · Dec 30, 2011





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

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


            Graphics2D g2 = (Graphics2D) g;
            g2.setFont(new Font("Serif", Font.PLAIN, 5));
            g2.setPaint(Color.black);
            drawString(g2,"Line 1\nLine 2", 120, 120);
            drawtabString(g2,"Line 1\tLine 2", 130, 130);