img
which encapsulates various information about a font. Let's begin by defining the common
terminology used when describing fonts:
Height
The top-to-bottom size of a line of text
Baseline
The line that the bottoms of characters are aligned to (not counting descent)
Ascent
The distance from the baseline to the top of a character
Descent
The distance from the baseline to the bottom of a character
Leading
The distance between the bottom of one line of text and the top of the next
As you know, we have used the drawString( ) method in many of the previous examples.
It paints a string in the current font and color, beginning at a specified location. However, this
location is at the left edge of the baseline of the characters, not at the upper-left corner as is
usual with other drawing methods. It is a common error to draw a string at the same coordinate
that you would draw a box. For example, if you were to draw a rectangle at coordinate 0,0,
you would see a full rectangle. If you were to draw the string "Typesetting" at 0,0, you
would only see the tails (or descenders) of the y, p, and g. As you will see, by using font
metrics, you can determine the proper placement of each string that you display.
FontMetrics defines several methods that help you manage text output. Several
commonly used ones are listed in Table 23-3. These methods help you properly display
text in a window. Let's look at some examples.
Method
Description
int bytesWidth(byte b[ ], int star t,
Returns the width of numBytes characters held in array b,
int numBytes)
beginning at star t.
int charWidth(char c[ ], int star t,
Returns the width of numChars characters held in array c,
int numChars)
beginning at star t.
int charWidth(char c)
Returns the width of c.
int charWidth(int c)
Returns the width of c.
int getAscent( )
Returns the ascent of the font.
int getDescent( )
Returns the descent of the font.
Font getFont( )
Returns the font.
int getHeight( )
Returns the height of a line of text. This value can be used
to output multiple lines of text in a window.
int getLeading( )
Returns the space between lines of text.
int getMaxAdvance( )
Returns the width of the widest character. ­1 is returned if
this value is not available.
int getMaxAscent( )
Returns the maximum ascent.
int getMaxDescent( )
Returns the maximum descent.
int[ ] getWidths( )
Returns the widths of the first 256 characters.
int stringWidth(String str)
Returns the width of the string specified by str.
String toString( )
Returns the string equivalent of the invoking object.
TABLE 23-3
A Sampling of Methods Defined by FontMetrics
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home