Font and FontMetrics Class

You can set fonts for the components  or subjects you draw, and use font metrics to measure font size. Fonts and font metrics are encapsulated in the classes Font and Fontmetrics.
Whatever the font is current will be used in the subsequent drawing. To set a font, you need to create a Font object from the Font class. The syntax is:

Font myFont = new Font(name, style, size);

Font names: SansSerif, Serif, Monospaced, Dialog and etc.
Style:  Font.PLAIN, Font.BOLD, Font.ITALIC

The style can be combined in the following code:

Font  oneFont = new  Font("Serif", Font.BOLD, 12);
Font otherFont = new  Font("Monospaced", Font.BOLD + Font.ITALIC, 16);

To find the fonts available on your systems, you need to create an instance of java.awt.GraphicsEnvironment using its static method getLocalGraphicsEnvironment( ).  GraphicsEnvironment is an abstract class that describes the graphics environment on a particular system. You can use its getAllFonts() method to obtain all the available fonts on the system, and its getsAvailableFontFamilyNames to obtain the names of all the available fonts.

Example:  The following statements will print all the available font names in the system:

GraphicsEnvironment  e  = GraphicsEnvironment.getLocalGraphicsEnvironment( );

String[ ]  fontnames = e.getAvailableFontFamilynames()

for (int i = 0; i< fontnames.length; i ++ )
       System.out.println(fontnames[i]);

FontMetrics can be used to compute the exact length and width of a string, which is helpful for measuring the size of the string in order to display it in the right position. A FontMetrics is measured by the following attributes:

Leading - the amount of space between lines of text.
Ascent - the height of a character, from the base line to the top.
Descent - the distance from the baseline to the bottom of a descending character, such as j, y and g.
Height - the sum of leading , ascent, and descent.

FontMetrics si an abstract class. To get FontMetrics object for a specific font, use the following getFontMetrics methods defined in the Graphics class:

public FontMetrics  getFontMetrics(Font f) - Returns the font metrics object of the specified font.

public FontMerics  getFontMetrics( ) - Return the font metrics object of the current font.

You can use these instance methods in the FontMetrics class to obtain to obtain font information:

public int getAscent()
public int getDescent()
public int getLeading()
public int getHeight()
public int stringWidth(string str)

Example  Using the FontMetrics class