How can I use a custom font in Java?
JavaFontsJava Problem Overview
I wrote a program in Java that uses a special font that by default doesn't exist on any operating system.
Is it possible in Java to add this special font to the operation system? For example, in Windows, to copy this font to the special Fonts folder.
If it is possible, how?
Java Solutions
Solution 1 - Java
If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:
[Oracle Java SE 6: java.awt.Font][1]
There is a [tutorial available][2] from Oracle that shows this example:
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.
An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.
[1]: http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#createFont%28int,%20java.io.File%29 "Font (Java Platform SE 6)" [2]: http://download.oracle.com/javase/tutorial/2d/text/fonts.html
Solution 2 - Java
Here is how I did it!
//create the font
try {
//create the font to use. Specify the size!
Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
//register the font
ge.registerFont(customFont);
} catch (IOException e) {
e.printStackTrace();
} catch(FontFormatException e) {
e.printStackTrace();
}
//use the font
yourSwingComponent.setFont(customFont);
Solution 3 - Java
From the Java tutorial, you need to create a new font and register it in the graphics environment:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
After this step is done, the font is available in calls to getAvailableFontFamilyNames()
and can be used in font constructors.
Solution 4 - Java
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)