Java Graphics How to - Draw and follow newline in Graphics2D.drawString








Question

We would like to know how to draw and follow newline in Graphics2D.drawString.

Answer

import java.awt.Graphics;
/*  w  w w. j  a  v a 2s. co m*/
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main 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 Main());
    f.setSize(220, 220);
    f.setVisible(true);
  }
}