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?
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