Determine Font Properties With FontMetrics

Determine Font Properties With FontMetrics

The java.awt.FontMetrics class provides information on the properties of a font. For example, it can be used to determine how many horizontal pixels are required (i.e., the width) when a single character or String of characters is drawn. This information is often important when drawing text using the java.awt.Graphics.drawString() method.

When writing by hand on lined/ruled paper, your letters normally “sit” on the line, with some lowercase letters, such as q, y, p, g, j being written partially below the line. In Java, the baseline represents that same line (or rule), and in general, most English characters will be drawn entirely above it. This is a source of confusion for many novice programmers, who assume that the y-coordinate in the drawString() method represents the upper-left corner of where the characters will be drawn, when in fact it represents the baseline. So, if you specify a value of zero as the y-coordinate in drawString, instead of the text appearing in the upper left corner of the screen, it will be drawn above the top of the displayable area. You can avoid this problem by using the font’s ascent value instead of zero, since the ascent identifies the height above the baseline needed to draw characters. For example, to draw a string at the upper left-hand corner of a component, you would use:

 public void paint(Graphics g) {	FontMetrics fontmet = getFontMetrics();	g.drawString("Hello, World!", 0, fontmet.getMaxAscent());}  //  public void paint()

FontMetrics also can be used to identify the vertical area below the baseline needed to draw characters (the descent), and the maximum width (i.e., number of horizontally adjacent pixels) needed to draw a character, also called the advance.


Share the Post: