The Java™ Tutorials
Hide TOC
Measuring Text
Trail: 2D Graphics
Lesson: Working with Text APIs

Measuring Text

To properly measure text, you need to learn a few methods and some mistakes to avoid. Font metrics are measurements of text rendered by a Font object such as the height of a line of text in the font. The most common way to measure text is to use a FontMetrics instance which encapsulates this metrics information. For example:

// get metrics from the graphics
FontMetrics metrics = graphics.getFontMetrics(font);
// get the height of a line of text in this
// font and render context
int hgt = metrics.getHeight();
// get the advance of my text in this font
// and render context
int adv = metrics.stringWidth(text);
// calculate the size of a box to hold the
// text with some padding.
Dimension size = new Dimension(adv+2, hgt+2);

This way is sufficient for many applications to evenly space lines of text or to size Swing components.

Note the following:

When using these methods to measure text, note that the text can extend in any direction outside of a rectangle, defined by the font height and the advance of the string.

This figure shows hot to measure text by using font metrics

Typically, the simplest solution is to ensure that the text is not clipped, for example, by components that surround the text. Add padding in cases where the text might otherwise be clipped.

If this solution is insufficient, other text measurement APIs in the Java 2D software can return rectangular bounding boxes. These boxes account for the height of the specific text to be measured and for pixelization effects.

Previous page: Physical and Logical Fonts
Next page: Advanced Text Display