klenium klenium - 2 months ago 27
Java Question

Can't set custom font

I'm working on a JavaFX project. I'd like to use custom font on a

from a CSS file. I've read and followd eg. this post.

public class Main extends Application {
public void init() {
Font font = Font.loadFont(getClass().getResourceAsStream("Dimitri_Swank.ttf"), 32);
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("Window.fxml"));
// ...

It prints
Font[name=Dimitri Swank, family=Dimitri Swank, style=Regular, size=32.0]
, so that the font is loaded successfully. The root container in the FXML file has a
attribute, and in this CSS file, there is a rule:

#gameName {
-fx-font-family: Dimitri Swank;
-fx-font-size: 32px;

The selector works well (it refers to a
), I can see the difference if I change the
. But the font family remains the default system font. What am I doing wrong?


As from JavaFX version 1.8u60 you can use plain css to load the font but with carefull that you need to use the exactly original name of the Font File,for example:

    src: url("../fonts/Younger than me Bold.ttf");

  -fx-font-family:"Younger than me";

Mention that the original name can be found opening the .ttf with a default editor and see it's name in case if you don't know it.

Complete tutorial:http://www.guigarage.com/2014/10/integrate-custom-fonts-javafx-application-using-css/

Have a look also here for your situation:Specifying external font in JavaFX CSS


The problem in your code is that in the css you are not adding double quotes " or single quotes ' around the font - family