Java Reference
In-Depth Information
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts(); // Get the fonts
You get a reference to the
GraphicsEnvironment
object for the current machine by calling the
static
method
getLocalGraphicsEnvironment()
. You then use the reference that is returned 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 are of a 1-point size. Characters with a point size of 1 are approximately 1/72 of an
inch, or 0.353 mm, so you should 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 six versions
but I'll only discuss three of them:
•
Font deriveFont(int Style)
: Returns a new
Font
object with the style specified — one of
PLAIN
,
BOLD
,
ITALIC
, or
BOLD+ITALIC
.
•
Font deriveFont(float size)
: Returns a new
Font
object with the specified point size.
•
Font deriveFont(int Style, float size)
: Returns a new
Font
object with the specified
style and point size.
You could use the last font from the array of
Font
objects to create an equivalent 12-point font with the
following statement:
Font newFont = fonts[fonts.length-1].deriveFont(12.0f);
Of the three other versions of
deriveFont()
, two involve an object of type
java.awt.geom.Affine
Transform
, but I'm deferring discussion of
AffineTransform
objects until Chapter 20. The third makes
use of a
Map
collection object containing special iterator objects for text attributes, but I don't discuss these.
Getting a
Font
object for every physical font in the system can be a time-consuming process if you have
many fonts installed. A much faster alternative is to get the physical 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
contains 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 outputs your primary display's size and resolution, as well as the list of font family names
installed on your machine:
import java.awt.Toolkit;
import java.awt.GraphicsEnvironment;
import java.awt.Font;
import java.awt.Dimension;