JavaFX - Register Font
In one of my previous [URL="http://fixunix.com/rakeshmenonp/entry/javafx_custom_fonts"]post[/URL] 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 - [URL="http://java.sun.com/javase/6/docs/api/java/awt/Font.html#createFont%28int,%20java.io.InputStream%29"]Font.createFont(int fontFormat, InputStream fontStream)[/URL] provides a way to create an instance of AWT font. Once loaded 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 - [URL="http://java.sun.com/javase/6/docs/api/java/awt/GraphicsEnvironment.html#registerFont%28java.awt.Font%29"]GraphicsEnvironment.registerFont(Font font)[/URL] for this purpose.
[B]Problem:[/B] [LIST] [*]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 [/LIST]
[B]Solution:[/B] [LIST] [*]Use [URL="http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html"]Java Reflection APIs[/URL] to invoke [URL="http://java.sun.com/javase/6/docs/api/java/awt/GraphicsEnvironment.html#registerFont%28java.awt.Font%29"]registerFont[/URL] method [*]Use [URL="http://java.sun.com/javafx/1.2/docs/api/javafx.async/javafx.async.JavaTaskBase.html"]JavaFX Asynchronous APIs[/URL] so as to execute above method in background thread [/LIST]
In below example, font - [URL="http://www.cdacmumbai.in/projects/indix/RaghuFonts/RRRaghuMalayalam.ttf"]RRRaghuMalayalam.ttf[/URL] 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.
<div id="RegisterFontApplet" style="text-align: left;">