The FontMetrics class is used to return the specific parameters for a particular Font object. An object of this class is created using the getFontMetrics() methods supported by the Component class and other classes, such as the Graphics and Toolkit classes. The FontMetrics access methods provide access to the details of the implementation of a Font object.
The bytesWidth(), charWidth(), charsWidth(), getWidth(), and stringWidth() methods are used to determine the width of a text object in pixels. These methods are essential for determining the horizontal position of text on the screen.
FontMetrics Useful Interface
Method | Returns | Notes |
bytesWidth(bytedatea[], int offset, int length) | Int | Returns the width (in pixels) of the bytes from offset for length |
charsWidth(bytedatea[], int offset, int length) | Int | Returns the width (in pixels) of the characters from offset for length |
charWidth(char c) | Int | How wide is this one character? |
charWidth(char c) | Int | How wide is this one character? |
getAscent() | Int | How much does a standard character rise above the baseline of the font? |
getDescent() | Int | How much does a standard character fall below the baseline of the font? |
getFont() | Font | What is the current font? |
getHeight() | Int | What is the standard height of this font? |
getLeading() | Int | What is the standard spacing between lines of this font? |
getMaxAdvance() | Int | What is the largest gap between characters? |
getMaxAscent() | Int | What is the largest rise above the baseline for this font? |
getMaxDescent() | Int | What is the largest fall below the baseline for this font? |
getWidths() | Int[] | Returns a 256 cell array of the advance widths for the first 256 characters in this font |
stringWidth(String str) | Int | This is how wide the string would be on screen (in pixels) |
import java.awt.*;
/* <APPLET CODE ="FontMetricsClass.class" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontMetricsClass extends java.applet.Applet
{
public void paint(Graphics g)
{
String s="Hello Java";
Font f=new Font("Arial",Font.BOLD+Font.ITALIC,20);
g.setFont(f);
FontMetrics met=g.getFontMetrics(f);
int ascent=met.getAscent();
int height=met.getHeight();
int leading=met.getLeading();
int baseline=leading+ascent;
for(int i=0;i<10;i++)
{
g.drawString("Line"+String.valueOf(i),10,baseline);
baseline+=height;
}
}
}