JavaFX – Register Font
In one of my previous post I discussed about how to bundle custom font along with application. Recently I came across another query related to registering a custom font. Java API – Font.createFont(int fontFormat, InputStream fontStream) provides a way to create an instance of AWT font. Once created the font needs to be registered so that it can be loaded using the font name or family name. JavaSE 6.0 and above has API – GraphicsEnvironment.registerFont(Font font) for this purpose.
Problem:
- API is available only since JavaSE 6.0, it may not be possible to use these APIs directly from JavaFX (which enforce JavaSE 5.0 compatibility)
- API involves loading of font over network, so we need to perform this operation in background thread so as to avoid freezing the user interface
Solution:
- Use Java Reflection APIs to invoke registerFont method
- Use JavaFX Asynchronous APIs so as to execute above method in background thread
In below example, font – RRRaghuMalayalam.ttf is downloaded from specified URL and registered. Launch application and click on “Register Font” button. The application is signed since it access resource from another domain.
For Applet mode, click on above image
Note: You may have to wait for a while until the font is downloaded from the URL and registered. Sample requires JavaSE 6.0 or above.
|
Try it out and let me know feedback
var dzone_style = ’2′;



Nice trick!
Very clever – the touch of the master
@Philippe Lhoste Thanks!
@Ernie Kent Thanks! I’m more of a messenger of masters..
Hi, Rakesh. If you can bear with me a bit further I have a question concerning this method. When I first tried it I thought the signing was required because the font was obtained from a different domain, which would not be a problem for us. However I now see that accessing the class in the local JRE also raises a security exception. Do you think it is possible to do something like this but package the method in a jar downloaded with the applet? Thanks!
Ernie
@Ernie I will look into this. I have sent you an email, please reply with more info.
Thanks, Rakesh
I did reply to your email last week. Basically the issue is that when using your method a signed applet seems to be required even when the font is loaded from the same place as the applet, The reason appears to be that accessing the JRE6 methods as done in your solution requires security privileges. I have found a different workaround by replacing the JRE5 jar in the JavaFX SDK and the Netbeans JAvaFX extension with a JRE6 jar. Netbeans then still flags an error on screen when RegisterFont is used, but the applet compiles and runs correctly.
Ernie