Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Aug 30, 2005

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;
		}
	}

}
Roberto Marquez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap