You've already seen one example of drawing text in the HelloWorldApplet program of the last chapter. You call the drawString() method of the Graphics object. This method is passed the String you want to draw as well as an x and y coordinate. If g is a Graphics object, then the syntax is

g.drawString(String s, int x, int y)

The String is simply the text you want to draw. The two integers are the x and y coordinates of the lower left-hand corner of the String. The String will be drawn above and to the right of this point. However letters with descenders like y and p may have their descenders drawn below the line.

Until now all the applets have used the default font, probably some variation of Helvetica though this is platform dependent. However unlike HTML Java does allow you to choose your fonts. Java implementations are guaranteed to have a serif font like Times that can be accessed with the name "Serif", a monospaced font like courier that can be accessed with the name "Mono", and a sans serif font like Helvetica that can be accessed with the name "SansSerif".

The following applet lists the fonts available on the system it's running on. It does this by using the getFontList() method from java.awt.Toolkit. This method returns an array of strings containing the names of the available fonts. These may or may not be the same as the fonts installed on your system. It's implementation dependent whether or not all the fonts a system has are available to the applet.

import java.awt.*;
import java.applet.*;

public class FontList extends Applet {

  private String[] availableFonts;

  public void init () {

    Toolkit t = Toolkit.getDefaultToolkit();
    availableFonts = t.getFontList();


  public void paint(Graphics g) {
    for (int i = 0; i < availableFonts.length; i++) {
      g.drawString(availableFonts[i], 5, 15*(i+1));

Available fonts
Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2002 Elliotte Rusty Harold
Last Modified February 13, 2002