Using Custom Fonts in Your JavaFX Application

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:

Standard system fonts Figure 1: Different Formatting Applied to Standard Fonts

When you run the following code, you will see the text similar to the previous window.

Source Code: Using Different Formatting Styles Applied to the Same Text String
...
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.

  1. Create fonts and META-INF folders in your project folder.
     
  2. Copy your font files to the fonts subfolder in your project.
    Note: Copy the entire font family to the fonts subfolder.
     
  3. Create a fonts.mf plain text file and place it in the META-INF folder. 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:
  4. Source Code: Names of and Paths to .ttf Files to Include in the Application
    corporate=/fonts/Company-corporate.ttf
    crazy-looking=/fonts/kidpr.ttf
              
  5. In your source code, specify the name of the font as follows:
  6. Source Code: Specifying the Name of the Font You Want to Include in Your Application
    ...
    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},
    ...
              

    Custom fonts 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.

Related Links