Java Reference
In-Depth Information
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts(); // Get the fonts
We get a reference to the GraphicsEnvironment object for the current machine by calling the
static method getLocalGraphicsEnvironment() as illustrated. We then use this to call its
getAllFonts() method. The getAllFonts() method returns an array of Font objects consisting
of those available on the current system. You can then check this list for the font you want to use. Each
of the Font instances in the array will be of a 1 point size, and since 1 point is approximately 1/72 of an
inch or 0.353mm, you will typically want to change this unless your screen and eyesight are really
exceptional. To change the size and/or style of a font you call its deriveFont() method. This method
comes in three versions, all of which return a new Font object with the specified size and/or style:
deriveFont() Method
Description
deriveFont(int Style)
Creates a new Font object with the style specified - one of
PLAIN , BOLD , ITALIC or BOLD+ITALIC .
deriveFont(float size)
Creates a new Font object with the size specified.
deriveFont(int Style,
float size)
Creates a new Font object with the style and size specified.
To use the last font from the array of Font objects to create an equivalent 12-point font you could write:
Font newFont = fonts[fonts.length-1].deriveFont(12.0f);
If you look in the documentation for the Font class, you will see that there is a fourth version of
deriveFont() that involves an AffineTransform , but we'll leave AffineTransform objects
until Chapter 18.
Getting a Font object for every font in the system can be a time-consuming process if you have many
fonts installed. A much faster alternative is to get the font names, and then use one of these to create the
Font object that you require. You can get the face names for all the fonts in a system like this:
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
The array fontnames will contain the names of all the font faces available, and you can use one or
more of these to create the Font objects you need.
Try It Out - Getting the List of Fonts
This program will output your screen size and resolution, as well as the list of font family names
installed on your machine:
import java.awt.*;
public class SysInfo
public static void main(String[] args) {
Search WWH ::




Custom Search