img
Font getFont( )
Once you have obtained the currently selected font, you can retrieve information about it
using various methods defined by Font. For example, this applet displays the name, family,
size, and style of the currently selected font:
// Display font info.
import java.applet.*;
import java.awt.*;
/*
<applet code="FontInfo" width=350 height=60>
</applet>
*/
public class FontInfo extends Applet {
public void paint(Graphics g) {
Font f = g.getFont();
String fontName = f.getName();
String fontFamily = f.getFamily();
int fontSize = f.getSize();
int fontStyle = f.getStyle();
String msg = "Family: " + fontName;
msg += ", Font: " + fontFamily;
msg += ", Size: " + fontSize + ", Style: ";
if((fontStyle & Font.BOLD) == Font.BOLD)
msg += "Bold ";
if((fontStyle & Font.ITALIC) == Font.ITALIC)
msg += "Italic ";
if((fontStyle & Font.PLAIN) == Font.PLAIN)
msg += "Plain ";
g.drawString(msg, 4, 16);
}
}
Managing Text Output Using FontMetrics
As just explained, Java supports a number of fonts. For most fonts, characters are not all the
same dimension--most fonts are proportional. Also, the height of each character, the length of
descenders (the hanging parts of letters, such as y), and the amount of space between horizontal
lines vary from font to font. Further, the point size of a font can be changed. That these (and
other) attributes are variable would not be of too much consequence except that Java demands
that you, the programmer, manually manage virtually all text output.
Given that the size of each font may differ and that fonts may be changed while your
program is executing, there must be some way to determine the dimensions and various
other attributes of the currently selected font. For example, to write one line of text after
another implies that you have some way of knowing how tall the font is and how many
pixels are needed between lines. To fill this need, the AWT includes the FontMetrics class,
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home