【发布时间】:2021-03-03 07:42:01
【问题描述】:
我正在尝试将自定义字体 Cerebri Sans Regular 设置为我的 JavaFX 应用程序。我正在使用 Java SE 11 和 JavaFX 11。
我的尝试:
public class SampleController implements Initializable {
@FXML
private Label customFont;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
Font font = Font.loadFont("cerebrisans-regular.ttf", 20);
customFont.setFont(font);
}
}
错误
java.lang.NullPointerException: Cannot invoke "javafx.scene.text.Font.getNativeFont()" because "<parameter1>" is null
at javafx.graphics/javafx.scene.text.Font$1.getNativeFont(Font.java:68)
css 的另一个尝试
@font-face {
src: url("cerebrisans-regular.ttf");
}
.root {
-fx-background-color: gray;
-fx-font-family: "Cerebri Sans"; /* this name is from font file */
}
.customFont {
-fx-text-fill: red;
-fx-font-size: 16px;
-fx-font-family: "Cerebri Sans";
}
错误
Mar 03, 2021 2:31:56 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load @font-face font [file:/C:/Java%20Training/JavaFX-Test/Custom-Font-Demo/bin/application/cerebrisans-regular.ttf]
【问题讨论】:
-
您的 CSS 文件中的
src: url("cerebrisans-regular.ttf")行是否缺少分号? -
@Ryan 我已经更新了问题并且错误已经改变。
-
@Ryan 是的。我已经在我的代码中尝试了它们,将样式表添加到 fxml 或 root.getStyleSheet()... 以及两者。不工作。同样的错误。
-
我知道了。谢谢你的帮助。在我的工作环境名称中,有一个空格,这就是问题所在。