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:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS