3

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
  • 617
  • 3
  • 16
  • 26
  • Possible duplicate of: [How to embed .ttf fonts is JavaFx 2.2?](http://stackoverflow.com/questions/16855677/how-to-embed-ttf-fonts-is-javafx-2-2) – jewelsea May 30 '15 at 08:16
  • 2
    It's similar. Let's keep this one up though for those working specifically with CSS in Scene Builder. I think it's a more convenient way to add fonts than through the Java code itself. – corpico May 31 '15 at 14:16
  • Isn't the accepted answer the same and Java code is still required for a custom font? – jewelsea May 31 '15 at 19:17
  • The accepted answer does provide the same Java code as your link, no it's not required. A custom font can be loaded entirely with CSS in Scene Builder using the _@font-face rule_. I accepted the Steven Van Impe's answer because he revealed that using @font-face requires that the font's name, not the font file's name, be used in the CSS, which solved my problem. The rest was extra info. – corpico Jun 01 '15 at 13:06

1 Answers1

13

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.

Steven Van Impe
  • 1,153
  • 8
  • 15
  • 2
    Thanks a lot! That did it! The font-family had to be named exactly as it is in the .ttf file. – corpico May 29 '15 at 19:32
  • 4
    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. – arturvt Dec 08 '15 at 19:43