JavaFX not finding all system fonts

2019-07-13 19:59发布

问题:

I've noticed that the JavaFX components I use, unlike their Swing counterparts, are not rendering some system fonts properly. Here's the complete example that presents the issue.

public class JavaFXApplication1 extends Application {

    @Override
    public void start(Stage primaryStage) {
        // Swing button
        SwingNode node = new SwingNode();
        SwingUtilities.invokeLater(() -> {
            JButton swingButton = new JButton("Comic Sans MS");
            swingButton.setFont(new java.awt.Font("Comic Sans MS", java.awt.Font.PLAIN, 20));
            node.setContent(swingButton);
        });

        // JavaFX button
        Button fxButton = new Button("Comic Sans MS");
        fxButton.setFont(Font.font("Comic Sans MS", 20));

        HBox hbox = new HBox();
        hbox.getChildren().addAll(node, fxButton);

        Scene scene = new Scene(hbox, 300, 250);
        primaryStage.setTitle("Font test");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

If you have the Comic Sans MS font in your system, you should see the following result. Only the Swing component looks fine:

Apparently the FX graphics system does not load all system fonts on startup. The most obvious solution is to load the missing ones manually, like that:

Font.loadFont(new FileInputStream(System.getenv("WINDIR")+"\\fonts\\"+"comic.ttf"), 20);

Now everything renders properly, but this solution isn't cross platform and I'd really expect it to work out-of-the-box just like it was in Swing. Am I missing something? If not, then why only a subset of system fonts is loaded into the JavaFX environment?

I'm running it on Windows 10.

回答1:

I figured out another thing: I created following code

String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailab‌​leFontFamilyNames(); for(String font: fonts) { System.out.printf("This is font %s %n", font);

This returns for example: This is font Something Strange (its a font which i downloaded and installed) so its available. But when I put it into this code:

<GridPane fx:controller="sample.Controller"
      xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10"
      style="-fx-font-family: Something Strange">

The text does not change at all. Maybe this contribute to your / our problem.