O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

308
|
Chapter 8, Rendering
#61 Load New Fonts at Runtime
HACK
Mac OS X’s font suitcases—a holdover from the Classic Mac
OS—aren’t supported. Your fonts need to be in .ttf files.
FontLoadingDemo, shown in Example 8-8, offers a straightforward applica-
tion of this font-loading technique. It takes the path to a .ttf file as its
command-line argument, creates an
InputStream, and creates a Font. It then
derives a plain, 32-point instance of the font, and uses that to put a sample
JLabel in a JFrame.
Testing Font Loading
All you need to run this demo is a .ttf file of a TrueType font, preferably one
not already installed on your system so you’ll know that the demo works.
There are many free and shareware fonts on the Web; I found the Marriage
Example 8-8. Loading fonts at runtime
public class FontLoadingDemo {
public static void main (String[] args) {
try {
// get font from path in args[0]
if (args.length < 1) {
System.out.println (
"usage: FontLoadingDemo path-to-ttf");
return;
}
File f = new File (args[0]);
FileInputStream in = new FileInputStream (f);
Font dynamicFont =
Font.createFont (Font.TRUETYPE_FONT, in);
Font dynamicFont32Pt =
dynamicFont.deriveFont (32f);
// draw something with it
JLabel testLabel =
new JLabel ("Dynamically loaded font \"" +
dynamicFont.getName( ) + "\"");
testLabel.setFont (dynamicFont32Pt);
JFrame frame = new JFrame ("Font Loading Demo");
frame.getContentPane( ).add (testLabel);
frame.pack( );
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace( );
}
}
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required