Finding & Displaying Fonts
Home ] Up ] JFrame Internal Structure ] Graphics Context ] Displaying Text ] Text & Fonts ] Mixing Fonts ] [ Finding & Displaying Fonts ]

 

 

There are only a small number of fonts that are guaranteed to be present in every Java environment:

  • Serif
  • SansSerif
  • Monospaced
  • Dialog
  • DialogInput

Each one of these is actually a logical font name, which is mapped to a specific platform-specific font on each platform.

For JDK 1.1 and up, the following font names are deprecated (the replacement name follows):

  • TimesRoman (use Serif)
  • Helvetica (use SansSerif)
  • Courier (use Monospaced)

The ZapfDingbats font is also deprecated in 1.1 on up, but only as a separate font name.

Here's a program that finds the fonts available to it, and displays them:

package swingExamples;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;

class AllFontsDisplayPanel extends JPanel
{
  public AllFontsDisplayPanel()
  {
    setBackground(Color.white);
  }
  
  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    
    int x = 10;
    int y = 20;
    Font font = null;
    FontMetrics fm = null;
    String fontString = null;
    for (int i = 0; i < m_font.length; i++)
    {
      String fontName = m_font[i];
      font = new Font(fontName, Font.PLAIN, 18);
      g.setFont(font);
      fm = g.getFontMetrics(font);
      if (i > 0)
        y += fm.getAscent();
      g.drawString( fontName, x, y );
      y += fm.getDescent() + fm.getLeading();
    }
  }
  
  private String[] m_font = 
          Toolkit.getDefaultToolkit().getFontList();
}

class AllFontsDisplayFrame extends JFrame
{
  public AllFontsDisplayFrame()
  {
    setTitle("AllFontsDisplay");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    Container contentPane = getContentPane();
    contentPane.add( new AllFontsDisplayPanel() );
  }
}

public class AllFontsDisplay
{
  public static void main(String[] args)
  {
    AllFontsDisplayFrame frame = new AllFontsDisplayFrame();
    frame.setVisible(true);
  }
}

and here's what it produces on my Windows XP system:

Note that the getFontList() method is deprecated.  We will see a program later that uses the preferred replacement for this method.

 

This page was last modified on 02 October, 2007