Home | Articles

Styled Text Tutorial
Lesson 1: Using Fonts

[Contents] [Next]

Styled text is essentially a simple text string drawn with a font. The font defines the text string size, and its overall look and feel. This lesson describes how to use the enhanced java.awt.Font class to create fonts. The next lesson explains how to use fonts to create and draw styled text.

What is a Font?

Dictionary of Terms

A font is a complete set of type in one point size and type face. For example, all English language characters and symbols in Helvetica 10 point bold face make up a font. The font defines the characteristic look, size, and style (bold, italics, or plain) of the text string that is drawn with the font.

How does a font define the characteristic look? A font is created from glyphs, and a glyph is a bitmapped image that defines the appearance of the characters or symbols in the font. All fonts within the same font family have a similar appearance because they are all made from the same glyph set. Likewise, different fonts families use different glyph sets to achieve their own distinguishing look.

A font family not only consists of fonts with a similar appearance, but also different points sizes and styles. Helvetica 10 point bold and Helvetica 12 point italic are two fonts in the same family, and Times Roman 8 point bold and Times Roman 10 point regular are two fonts in a different font family.

Find Available Fonts

To use a font, you have to create a Font object, and to do that, you need to know what fonts are available on the system and their names. Fonts have logical, family and font names. The logical name is a name mapped onto one of the specific fonts available on the platform.

To get the logical name for a Font object, call java.awt.Font.getName.

The family name is the name of the font family that determines the typographic design across several faces, such as Helvetica or Times Roman.

To get the family name for a given Font object, call java.awt.Font.getFamily.

The font name represents a specific font within a family such as Helvetica Bold.

To get the font name, call java.awt.Font.getFontName, and to determine which font faces are available on a system, call java.awt.GraphicsEnvironment.getAllFonts.

Creating and Deriving Fonts

font samples The easiest way to create a font is by specifying the font name, point size, and style. Once you have a Font object, you can derive any number of new Font objects by calling the Font.deriveFont method on the existing font and specifying a new point size, style, transform (position, slant, scale, or rotation), or attribute map.

  Font boldFont = new Font("Helvetica", Font.BOLD, 12);
  Font italicDerived = boldFont.deriveFont(Font.ITALIC, 12);
  Font plainDerived = boldFont.deriveFont(Font.PLAIN, 14);

Once you have a font, you can use it to create a TextLayout object and draw styled text, which are the topics of the next lesson.

© 1994-2005 Sun Microsystems, Inc.