You can apply different fonts to the text in your applications. A font is represented by the Font class, which is included in the net.rim.device.api.ui package. Each font has a style that is specified by using the style bits that are defined in the Font class, such as Font.BOLD, Font.ITALIC, and Font.PLAIN. Each font also has a size, which refers to the height of the font in a particular unit of measurement (points, millimeters, or pixels). A Font object cannot be altered after it is created, so you can use a reference to a Font object and be sure that the font that it refers to always has the same style and size. To set the font for a field, you can invoke Field.setFont(Font).

You can use methods of the Font class to retrieve various font properties. You can invoke getHeight() to retrieve the height of the font (in pixels), which can be useful if you create a custom field and need to implement Field.layout() to place text in a field's content area. You can also invoke isBold(), isItalic(), isUnderlined(), and isPlain() to determine the style of the font. If you want to retrieve the default font that is currently set on the BlackBerry® device, you can invoke the static Font.getDefault().

To create Font objects that you can apply to text, you can use the FontFamily class. A font family is a collection of fonts of differing sizes and styles that belong to the same typeface and use the same font family name. For example, BBAlpha Sans and Times New Roman are two font families that are available in the BlackBerry® Java® SDK.

You can use FontFamily as a factory to create Font objects that have specific styles and sizes. You can invoke the static FontFamily.forName(String), which returns a FontFamily object that corresponds to the font family name that you specify. For example, the following code sample retrieves a FontFamily object that corresponds to the BBMillbank font family:

    FontFamily fontFam = FontFamily.forName("BBMillbank");
catch (ClassNotFoundException e)
    System.out.println("The specified font family was not found.");

The FontFamily.forName(String) method throws a ClassNotFoundException if the specified font family is not registered on the device, so it's important to catch this exception when you try to retrieve a FontFamily object using this method. You can retrieve a list of all font families that are registered on the device by invoking the static FontFamily.getFontFamilies().

After you retrieve a FontFamily, you can invoke getFont(int, int) to retrieve a Font object with the specified style and size that is part of that font family. For example, if fontFam is a FontFamily object that represents the BBMillbank font family, then you can invoke fontFam.getFont(Font.BOLD, 18) to retrieve a Font object of this font family with a bold style and a height of 18 pixels.

Next topic: Measuring text

Was this information helpful? Send us your comments.