devxlogo

Locating the Fonts Available to Your Java Apps

Locating the Fonts Available to Your Java Apps

One way to find which fonts are available to your Java programs is to call the getFontList method of the java.awt.Toolkit class. It returns an array of font names. Although just a few are given, these names can be used to create a font instance:

Toolkit toolkit = getToolkit();String[] fontNames = toolkit.getFontList();

The problem with this method is that the getFontList method has been deprecated. As of Java 1.2, the recomended way to find the fonts available to a JVM is to use java.awt.GraphicsEnvironment’s getAvailableFontFamilyNames method. It generally provides a longer list of names.

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();String[] fontNames = ge.getAvailableFontFamilyNames();

The following class can be used to preview the fonts. Its constructor takes a String array of font names. Once the object has been created, simply add it to a java.awt.Container or a sub-class of thereof:

import javax.swing.JPanel;import java.awt.Graphics;import java.awt.Font;import java.awt.Color;class FontPanel extends JPanel {	String [] fontNames;	public FontPanel(String [] fonts) {		fontNames = fonts; 	}	public void paint(Graphics g) {		g.setColor(Color.black);		int y = 20;		for (int f = 0; f < fontNames.length; f++) {			g.setFont(new Font(fontNames[f],Font.PLAIN,16) );			g.drawString(fontNames[f] + ": The quick brown fox jumps over the lazy dog.", 10, y);			y += 20;		}	}}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist