Search code examples
javajavafxjava-8javafx-2javafx-8

JavaFx Could not load @font-face font because of com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged


I had already asked a similar question here but it seems It wasn't clear since I had a lot of code in the project and couldn't post it here So please don't mark as duplicate.

Because of that, I then decided to create a new project with just a Label in it to make the code small and clean and also to eliminate other potential suspects of the error I'm getting.

So here is my Java Source code

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Group root = new Group();

        Label label = new Label("Sample Label");
        label.setId("sampleLabel");
        root.getChildren().add(label);

        Scene scene = new Scene(root, 300, 275);
        scene.getStylesheets().add(getClass().getResource("applicationStyles.css").toExternalForm());
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

And this is my css file

/**/
@font-face {
    font-family:'Roboto';
    src:url("Roboto-Thin.ttf");
}
#sampleLabel{
    -fx-font-family: Roboto ;
}

This is the error I'm getting in Intellij Idea

Dec 02, 2015 9:16:34 AM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load @font-face font [file:/C:/Users/UserName/Desktop/Java8%20projects/TeamViewer/out/production/TeamViewer/sample/Roboto-Thin.ttf]

All the project files are in one package and the font file is also present in the out>production>TeamViewer>sample>Roboto-Thin.ttf. I also upgraded from jdk-8u65 to jdk-8u66

Thanks, any help is greatly appreciated.


Solution

  • I found the possible cause and a work-around: Under the hood the css-loader uses the function Font.loadFont to load the font-face in your CSS. Font.loadFont simply returns null if it fails, which give the "warning".

    It seems that this function does not work with %20 it its path/url-string. So you need to resolve the path and then replace it with a space. That means you will have to load your fonts with code in stead of with CSS (for now).

    In Clojure my work-around looks like this:

    (require '[clojure.java.io :as cio])
    (require '[clojure.string :as s])
    (-> "fonts/SourceCodePro-Regular.ttf" 
      cio/resource 
      str 
      (s/replace "%20" " ") 
      (javafx.scene.text.Font/loadFont  10.))
    

    ;-)