Using Custom Fonts in Your JavaFX Application
- Skill Level Intermediate
- Product JavaFX
- Key Features API
- Last Updated September 2009
When you create your JavaFX application, you want it to look different from other applications, and one way to do that is to alter the text layout. Even with the standard system fonts you can change the size, color, and many other properties of the text as in the following example:
Figure 1: Different Formatting Applied to Standard Fonts
When you run the following code, you will see the text similar to the previous window.
...
var string = "The Quick Red Fox";
...
...
content:[
VBox{
spacing: 10
content:[
Text{y: 15 content: string},
Text{y: 15 content: string font: Font{size: 30}},
Text{y: 15 content: string stroke: Color.RED font: Font{name:"Verdana"}},
Text{y: 15 content: string smooth: false font: Font{size: 20}},
Text{y: 10 content: string translateX: 0 translateY: 10 rotate: 180}
]
}//VBox
]
...
Note: For more information about using the standard fonts, see the Text chapter in the Quick JavaFX GUI Overview of the Building GUI Applications With JavaFX tutorial.
But, what if you need to use some unique fonts that might not be installed on other people's computers? For example, suppose that you are creating an application for your corporate web site and you want your application to have a corporate look and you need to use the fonts approved by your marketing department. Or, you are deploying a new game and your designer created a crazy-looking font for it.
To include a true type font (.ttf) in your JavaFX application, use the following procedure.
- Create
fontsandMETA-INFfolders in your project folder.
- Copy your font files to the
fontssubfolder in your project.
Note: Copy the entire font family to thefontssubfolder.
- Create a fonts.mf plain text file and place it in the
META-INFfolder. JavaFX runtime picks up fonts information from this file. The file must contain names that you will use in your source code and paths to font files in the following format:
- In your source code, specify the name of the font as follows:
corporate=/fonts/Company-corporate.ttf
crazy-looking=/fonts/kidpr.ttf
...
Text{y: 15 content: "Company Corporate" font: Font{name:"corporate" size: 22}},
Text{y: 60 content: "Game Title" font: Font{name:"crazy-looking" size: 40} stroke: Color.RED},
...
Figure 2: Custom Fonts
After you include a font in your JavaFX application you can be sure that it looks exactly the way you want it to look regardless of the fonts installed on the user's system.
Note: Mobile devices currently do not support the loading of custom fonts.
Related Links
We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of repliesyour information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.
Dmitry Kostovarov
Technical Writer, Sun Microsystems