How to set custom fonts in JavaFX Scene Builder using CSS

12,926

Make sure to use Font.loadFont to actually load the font on application startup. Then you should be able to use the font from CSS. Be careful to use the font's name, not the font file's name. That's a common mistake.

I have used the following before to load and use a custom font:

Font.loadFont(getClass().getResourceAsStream("/resources/fonts/marck.ttf"), 14);

and:

-fx-font-family: "Marck Script";

FYI: the quotes are only needed if the name contains a space.

Share:
12,926
corpico
Author by

corpico

I spend my days in front of a slim box of lights trying to make the lights change in favorable ways. Some days the lights don't cooperate and I need StackExchange to save the day.

Updated on June 07, 2022

Comments

  • corpico
    corpico almost 2 years

    I'm making a GUI in JavaFX Scene Builder and would like all text (Labels, Text Fields, Comboboxes) to use the same font. The problem is it's a custom font that likely won't be on every client's computer.

    I've tried CSS:

    @font-face {
       font-family: DIN;
       src: url(DIN.tff);
    }
    
    .text {
       -fx-font-family: DIN;
       -fx-font-style: bold;
    }
    

    Saved the above code to file Font.css and tried applying it to each GUI element through Scene Builder's JavaFX CSS fields, but it's not working.

    Have I made a mistake in the CSS? Or is there a better way to go about this? I'd prefer not to have to load the font and set it for every element in the Java code itself if I don't have to.

  • corpico
    corpico almost 9 years
    Thanks a lot! That did it! The font-family had to be named exactly as it is in the .ttf file.
  • arturvt
    arturvt over 8 years
    Quick tip: When you load the font, check the name by getName() so you can add exactly the expected name. Sometimes it's not just the font name.