2

I'm working on a JavaFX project. I'd like to use custom font on a Label from a CSS file. I've read and followd eg. this post.

public class Main extends Application {
    @Override
    public void init() {
        Font font = Font.loadFont(getClass().getResourceAsStream("Dimitri_Swank.ttf"), 32);
        System.out.println(font);
    }
    @Override
    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 stylesheets="@Window.css" 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 Label), I can see the difference if I change the -fx-font-size. But the font family remains the default system font. What am I doing wrong?

Community
  • 1
  • 1
klenium
  • 2,468
  • 2
  • 24
  • 47
  • In your linked post's answer, I saw that they had their `-fx-font-family` in quotes, did you try doing `-fx-font-family:'Dimitri Swank';`? – Hypnic Jerk Nov 07 '16 at 22:59
  • @MichaelPickett lol that's so easy, and it solved the problem, thanks. – klenium Nov 07 '16 at 23:08

1 Answers1

0

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:

@font-face{
    src: url("../fonts/Younger than me Bold.ttf");
}

.button{
  -fx-background-color:white;
  -fx-background-radius:15.0;
  -fx-font-size:18.0;
  -fx-font-family:"Younger than me";
  -fx-text-fill:black;
  -fx-font-weight:bold;  
}

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


Finally:

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

Community
  • 1
  • 1
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93