簡體   English   中英

如何在 JavaFX 中設置自定義字體?

[英]How to set custom font in JavaFX?

我正在嘗試將自定義字體“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 代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM