Java Reference
In-Depth Information
can be displayed in one of three styles: plain, bold, or italic. The JVM assigns
an actual font to each of these logical names from the fonts available on the
system.
Yo u pass the font specification in the constructor of the Font class. For exam-
ple, the following code draws the word Test with the font for Monospaced ,
plain, and 24-point size:
public void paintComponent (Graphics g) {
g.setFont (new Font ( " Monospaced " , Font.PLAIN, 24);
g.drawString ( " Test " , 10, 10);
}
Pay close attention to the parameter list of the Font constructor. The first param-
eter is a string. To use one of the logical font names, it must exactly match one
of the five logical names given above. Unfortunately, the Font class does not
define constants for those names, so you must be sure to type it exactly cor-
rectly or unexpected results occur. The second parameter is an int identifying
the font style. The constants PLAIN , BOLD , and ITALIC are provided in the
Font class to specify the style. The third parameter is an int giving the point
size.
When a string str is drawn with g.drawString (str, x, y) , the
x and y parameters (both int type) give the position of the baseline of the
first character in the string (see Figure 6.7(a)). It will be drawn with the graphic
context's current color and font.
Yo u might assume that the Font class includes methods to provide detailed
information about the font, but instead the FontMetrics class provides
that information. After the font is set, an instance of FontMetrics can be
obtained from the graphics context using the getFontMetrics() method. The
(a)
Figure 6.7 (a) Font
metrics definitions.
(b) This applet displays
text with the
DrawTextPanel class.
(b)
Search WWH ::




Custom Search