javajavafxjava-11javafx-11

JavaFX Font not being rendered correctly



public class Main extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Hello World!");

        Button btn = new Button();
        btn.setText("Hello");
        btn.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });

        StackPane root = new StackPane();
        root.getChildren().add(btn);
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }
}

Getting following first lines on console:

35026:1978749] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:]. 2021-06-09 00:00:46.808 java[35026:1978749] CoreText note: Set a breakpoint on CTFontLogSystemFontNameRequest to debug. 2021-06-09 00:00:46.815 java[35026:1978749] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:]. 2021-06-09 00:00:46.982 java[35026:1978817] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:].

OS: macOS javafx-sdk-11.0.2 jdk 11

instead of Hello getting following text on button enter image description here


Solution

  • The issue is that you do not have the font: ".SFNS-Regular" either installed or configured correctly so that JavaFx can tell where it is. I'm actually not sure if it is because of the font not being installed/configured correctly but....

    What I had to do to resolve this was to add:

    * {
       -fx-font-family: 'serif'
    }
    

    in my root CSS file. If you are not using CSS files or are using inline styles, then you can still set a global font:

    Instead of this:

    primaryStage.setScene(new Scene(root, 300, 250));
    

    You can do something like this:

    Scene scene = new Scene(root, 300, 250);
    scene.getRoot().setStyle("-fx-font-family: 'serif'");
    primaryStage.setScene(scene);
    

    You can read more about JavaFX fonts here as well as additional CSS configurations for the components. Using CSS files is a great way to separate the component styles from their logic and if you have created web pages before, it will feel very familiar and really easy to pick up.