![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e652. Getting the Font Faces for a Font FamilyTo create aFont object to draw text, it is necessary to specify
the font face name. This example demonstrates how to retrieve all the
font face names from a font family name. Unfortunately, the method is
somewhat inefficient since it involves creating one-point size
Font objects for every available font in the system. The example
caches all the information by creating a hash table that maps a font
family name to an array of font face names.
See also e651 Listing All Available Font Families. Note: J2SE 1.4 only support True Type fonts. Map fontFaceNames = new HashMap(); // Get all available font faces names GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font[] fonts = ge.getAllFonts(); // Process each font for (int i=0; i<fonts.length; i++) { // Get font's family and face String familyName = fonts[i].getFamily(); String faceName = fonts[i].getName(); // Add font to table java.util.List list = (java.util.List)fontFaceNames.get(familyName); if (list == null) { list = new ArrayList(); fontFaceNames.put(familyName, list); } list.add(faceName); } // Replace the face name lists with string arrays, // which are more compact and convenient to use for (Iterator it=fontFaceNames.keySet().iterator(); it.hasNext(); ) { String familyName = (String)it.next(); java.util.List list = (java.util.List)fontFaceNames.get(familyName); fontFaceNames.put(familyName, list.toArray(new String[list.size()])); } // Use the table String[] faces = (String[])fontFaceNames.get("Verdana");
e653. Drawing a Paragraph of Text e654. Getting the Shape from the Outline of Text e655. Drawing Text with Mixed Styles © 2002 Addison-Wesley. |