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.

See also  Why ChatGPT Is So Important Today

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist