Java's FontMetrics class allows the height, leading, ascent, and descent to be found for a Font object. This information is useful when graphics objects must be placed precisely relative to some text. For example, if we want to underline some text, we might wish the underline to appear exactly at the location of the descent of the font. The following applet show an example of the use of the FontMetrics class, together with a few other useful methods dealing with fonts.

Some information on the font being used is drawn to the screen, and this information is used to draw a neat box around two of the labels. After setting the font to be Times Roman, bold, and 14 point, we use the getFont() method of the Graphics class to obtain a Font object containg this font. We could of course, have achieved the same result by saving the result of the call to the Font constructor in the Font object currentFont, but we wanted to show the use of the getFont() method. Next, a FontMetrics object is created an initialized to the properties of currentFont by using the getFontMetrics() medthod of the Graphics class. The currentFontMetrics object is then used to obtain the ascent, descent, leading, and height of the font, using the corresponding methods from the FontMetrics class. We use the getFontList() method of the Toolkit class to obtain a list of the available fonts in the current Java installation. This may be useful, for example, if you use an exotic font in your applet and want to check to see if that font is available on another system.

Canvases