如何在JavaFX中从CSS设置自定义字体?

Hex*_*rks 5 css fonts javafx

我在src/main/resources文件夹(RobotoMono.ttf)中向项目添加了自定义字体。然后我尝试从CSS文件中加载它,如下所示:

@font-face {
    font-family: 'RobotoMono';
    src: url('RobotoMono.ttf');
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试将此字体设置为某种字体时,它不起作用:

.column-header-label {
    -fx-label-padding: 0;
    -fx-text-overrun: clip;
    -fx-font-family: 'RobotoMono';
}
Run Code Online (Sandbox Code Playgroud)

如果我将字体设置为系统上存在的某种字体,则可以看到字体发生了变化,但是我包含的字体不起作用。

我究竟做错了什么?

Ron*_*ven 5

In your css, you have to specify a font-face with a url. Then, in your css element you have to use the name of the font from inside the ttf file, not the name of the font file itself. For instance, if you open the ttf file from Windows you see "Roboto Mono".

@font-face {
    src: url('RobotoMono.ttf');
}

.column-header-label {
    -fx-label-padding: 0;
    -fx-text-overrun: clip;
    -fx-font-family: 'Roboto Mono';
}
Run Code Online (Sandbox Code Playgroud)

  • 只是提醒大家,`@font-face` 应该放在你的 CSS 中的第一个,以便它被选中! (2认同)