使用JavaFX 8和CSS

时间:2017-05-16 09:06:24

标签: css fonts javafx-8

我正在尝试使用Apple's San Francisco font为我的Java应用程序设置外观。我已经尝试了我找到的每种方法,但仍然无法加载SF字体,而其他自定义字体似乎有效。

以下是我的CSS代码,如果我使用this answer中的TRON字体但不使用SF字体,则可以使用。 ID为title的元素是Label对象,其中文本在构造函数中设置,除了设置ID之外,不执行任何其他操作。 From here,我知道这应该有效。知道为什么不这样做吗?

(请注意,只要适用,我还尝试过“旧金山”,“SF”,“SF UI”和“SF UI文本”代替“SF UI Text Regular”。)

@font-face {
    src: url("SFText-Regular.otf");
}

#title .text {
    -fx-font-family: "SF UI Text Regular";
}

我正在使用Java 1.8.0_121-b13和JavaFX 8.0.121-b13。

我尝试过的其他方法

旧的CSS方法无济于事:

@font-face {
    font-family: "SF";
    src: url("SFText-Regular.otf");
}

#title .text {
    -fx-font-family: "SF";
}

加载并设置字体内联(from here):

title.setFont(Font.loadFont("file:SFText-Regular.otf", 10));
title.setStyle("-fx-font-family: 'SF UI Text Regular';");

最后单独加载字体(from here):

Font.loadFont(ControlPane.class.getResource("SFText-Regular.otf").toExternalForm(), 10);
        title2.setStyle("-fx-font-family: 'San Francisco';");

所有上述工作都适用于TRON字体,但不适用于SF字体。这个问题是否可能源于他们的设计或类似的东西?

1 个答案:

答案 0 :(得分:1)

这对我有用:

  1. 从<:p>下载字体

    https://www.fontify.me/cm/28ea2e32b70da0a2480848ba03cd6146/SF-UI-Text-Regular.ttf

      

    这只是来自互联网的随机链接,我不知道它是否会保持良好状态。

  2. 将下载的字体放在与下面示例代码相同的目录中。
  3. 右键单击OS X中的文件,然后选择“获取信息”以查找字体名称。
      

    在这种情况下,它是:SF UI Text Regular

  4. 调试示例代码。
  5. 使用SF UI Text Regular字体:

    sample

    使用OS X 10.9.5框中的默认字体(在代码中注释掉setStyle行):

    default

    与所提供的低质量屏幕截图相比,这种差异很微妙,但在我的电脑上并排运行两个屏幕时更为明显。

    我使用的字体是.ttf字体而不是.otf字体。我不知道这是否有所作为。

    不幸的是,我无法充分解释为什么苹果会从树上掉下来。

    SAN-fran.css

    @font-face {
        src: url("SF-UI-Text-Regular.ttf");
    }
    

    SanFranFont.java

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class SanFranFont extends Application {    
        @Override
        public void start(final Stage stage) throws Exception {
            Label text = new Label("After dinner, the weather being warm, we went into the garden and drank thea, under the shade of some apple trees...he told me, he was just in the same situation, as when formerly, the notion of gravitation came into his mind. It was occasion'd by the fall of an apple, as he sat in contemplative mood. Why should that apple always descend perpendicularly to the ground, thought he to himself...");
            text.setWrapText(true);
            text.setPrefWidth(400);
    
            final Scene layout = new Scene(new StackPane(text));
            layout.getStylesheets().add(
                    getClass().getResource("san-fran.css").toExternalForm()
            );
    
            text.setStyle("-fx-font-family: \"SF UI Text Regular\";");
    
            stage.setScene(layout);
            stage.show();
        }
    
        public static void main(String[] args) throws Exception {
            launch(args);
        }
    }