Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break lines in g.drawString in Java SE [duplicate]

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??

like image 897
ArMEd Avatar asked Dec 30 '11 06:12

ArMEd


1 Answers






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

 
like image 139
Rupok Avatar answered Sep 29 '22 23:09

Rupok