Drawing Simple Text - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Drawing Simple Text

Demo Code

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;

public class Main {
  public void paint(Graphics g) {
    // Set the desired font if different from default font
    String family = "Serif";
    int style = Font.PLAIN;
    int size = 12;
    Font font = new Font(family, style, size);
    g.setFont(font);/*ww  w .ja  va2s .  co  m*/

    // Draw a string such that its base line is at x, y
    int x = 10;
    int y = 10;
    g.drawString("aString", x, y);

    // Draw a string such that the top-left corner is at x, y
    x = 10;
    y = 30;
    FontMetrics fontMetrics = g.getFontMetrics();
    g.drawString("aString", x, y + fontMetrics.getAscent());
  }
}

Related Tutorials