Java Notes

FontMetrics

The java.awt.FontMetrics class is used to determine the measurements of characters and strings. These measurements can be used to precisely position text.

Some font terminology

baselineThe position at the bottom of characters, but above their descenders. The y coordinate of drawString specifies the baseline position.
advance widthThe horizontal width of a character or string.
ascentThe distance above the baseline of a character or string.
descentThe distance below the baseline of a character or string.
leadingThe vertical spacing between baselines of a font.

Getting a FontMetrics object

Font metrics are determined by the font and the graphics context. To create a FontMetrics object, where g is a Graphics object and f is a Font object:

FontMetrics fm = g.getFontMetrics(f);

FontMetrics methods

The following variables stand for something of a given type: i (int), c (char), s (String), g (Graphics).

MethodDescription
i = fm.getAscent();Returns ascent for font
i = fm.getDescent();Returns descent for font
i = fm.getLeading();Returns leading for font
i = fm.charWidth(c);Advance of char c.
i = fm.stringWidth(s);Advance width for String s.
Rectangle2D r = fm.getStringBounds(s, g); Returns bounding box for the string.

Webliography