Getting the Dimensions of Text From within the paint() method - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

Getting the Dimensions of Text From within the paint() method

Demo Code


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

public class Main {

  public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Font font = new Font("Serif", Font.PLAIN, 12);
    FontMetrics fontMetrics = g2d.getFontMetrics();

    int width = fontMetrics.stringWidth("aString");
    int height = fontMetrics.getHeight();
  }/*from ww  w.j av  a  2s.c om*/
}

Related Tutorials