Trail: 2D Graphics
Lesson: Working with Text APIs
Measuring Text
Home Page > 2D Graphics > 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:

Previous page: Selecting a Font
Next page: Advanced Text Display

Discuss
We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies — your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.