Font Awesome Icons in JavaFX (Part 3/3)

In order to use Font Awesome in FXML, we have to reference it through a ResourceBundle. Using the font icon value directly on the FXML element will not work and it will throw an exception during the FXML processing (for example <Label text="\uf13c"/>).

First, we need to prepare and load a properties file with the icon definitions. We can obtain the values for the icons from the original font-awesome.css file. To avoid conflicts with other resource bundles, we can use the prefix "fa" for the icon names:

fa.compass=\uf14e
fa.compress=\uf066
fa.connectdevelop=\uf20e
fa...
devlabs=ninja :)

For convenience, we add this file in the same place inside the project structure as the fontawesome-webfont.ttf file:

src/main/resources/fa/fontawesome-webfont.ttf
src/main/resources/fa/fontawesome.properties

The only remaining task is to introduce the properties file to the application. This is easily done with ResourceBundle:

@Override
public void start(Stage stage) throws Exception {
  FXMLLoader loader = new FXMLLoader();
  loader.setResources(ResourceBundle.getBundle("fa.fontawesome"));
  // ... 
}

In the above example the ResourceBundle containing the icons was loaded in the Application#start method and is available to all controllers in the application.

Finally, to use the icons font in fxml, we simply need to use it in the same manner as an internationalized string:

<Label text="%fa.compass" />

Resources