Font

The Font class is Java's way of representing font information. It specifies the size and style of text, as well as the font to use. It is part of the java.awt package, so you need to import at the top of each java file where you want to use it:

import objectdraw.*;
import java.awt.Font;

public class ....

Using the Font class is the easiest way to set the font and style of a Text. You will also use it later on with GUI components. Having used word processing programs all your lives, you are no doubt familiar with ideas like font size, styles, and the names of some common fonts.

Table of Contents

1. Font.decode() - the only method you really need to know

It is likely that the only method you will use in the Font class is this one, which requests a Font object to represent a given style:

public static Font decode(String str)

The String I pass along to decode() has to be in a special format, with the font name, then the style, then the size. I would use it like this:

text.setFont(Font.decode("Times-BOLD-18"));
text.setFont(Font.decode("Courier-PLAIN-24"));
text.setFont(Font.decode("Helvetica-ITALIC-6"));
text.setFont(Font.decode("Arial-BOLDITALIC-14"));

If the font name you ask for doesn't exist on the computer running the applet, it will substitute a different font instead (usually Times).

2. Getting information from a Font object

You can probably guess what all these methods are useful for:

public String getFontName();
public int getSize();
public boolean isBold();
public boolean isItalic();
public boolean isPlain();
public int getStyle();

The style here is a combination of styles defined as constants in the Font class. They are called, appropriately enough, Font.BOLD and Font.ITALIC. The value returned from getStyle() will be a sum of the styles being used; I can test which styles are there using the bitwise & "and" operator:

if(font.getStyle() & Font.ITALIC != 0) {

It is also possible to derive one font from another, making a new Font that changes just the size or style of an existing Font:

public Font deriveFont(int size)
public Font deriveFont(int size, int style)

So, for example, suppose that I want to resize a font to size 24 and make it bold if it wasn't already. I want it to stay italic if it already was. So, I'll ask it to derive a font, giving 24 as the size, and for the style I'll use its current style, combined with Font.BOLD using the bitwise | "or" operator:

font = font.deriveFont(24, font.getStyle() | Font.BOLD)

3. Full specification for the Font class

You can read the full specification for the Font class here on the java website:

http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Font.html