'How to set custom font in JavaFX?
I'm trying to set the custom font "Cerebri Sans Regular" to my JavaFX application. I'm using Java SE 11 and JavaFX 11.
My tries:
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);
}
}
Error
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)
Another try from 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";
}
Error
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]
Solution 1:[1]
The problem was in my working environment name, there was a space. Removed, renamed and now it is working with the CSS code shown in the question.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ms. Siri |
