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:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several