问题
I wanted to change a (loaded) text font dinamically for my javafx application, so I did this code:
Font font = Font.loadFont(Fonts.class.getClassLoader().getResource("path/font.woff").toExternalForm(), 25);
Font bold = Font.font(font.getFamily(), FontWeight.BOLD, font.getSize());
Font italic = Font.font(font.getFamily(), FontPosture.ITALIC, font.getSize());
Font boldItalic = Font.font(font.getFamily(), FontWeight.BOLD, FontPosture.ITALIC, font.getSize());
but when I try to change the text font to bold or italic nothing changes, and I don't seem to locate some method like the one in java.awt.Font#deriveFont where you could derive italic or bold from another font.
Code to apply the font:
public void applyFont(javafx.scene.text.Text text) {
text.setFont(font);
}
EDIT: More log:
I put some log that says what font is he getting and prints the Font#toString() result:
getFont(bold=false, italic=false) -> Font[name=<Name> Regular, family=<Name>, style=Regular, size=25.0]
getFont(bold=true, italic=false) -> Font[name=<Name> Regular, family=<Name>, style=Regular, size=25.0]
getFont(bold=false, italic=true) -> Font[name=<Name> Regular, family=<Name>, style=Regular, size=25.0]
getFont(bold=true, italic=true) -> Font[name=<Name> Regular, family=<Name>, style=Regular, size=25.0]
But if I replace the first line of code in the font loading with
font = Font.font(null, 25);//get the system's default font
It works and I get this output:
getFont(bold=false, italic=false) -> Font[name=System Regular, family=System, style=Regular, size=25.0]
getFont(bold=true, italic=false) -> Font[name=System Bold, family=System, style=Bold, size=25.0]
getFont(bold=false, italic=true) -> Font[name=System Italic, family=System, style=Italic, size=25.0]
getFont(bold=true, italic=true) -> Font[name=System Bold Italic, family=System, style=Bold Italic, size=25.0]
回答1:
You need to load another font file, that will provide appropriate Posture or Weight.
For every popular font (including System, that is used, when you call Font.font(null, 25)
) there are several font files in the system: one for regular, one for italic, one for bold etc.
For instance, for Times New Roman there are four files in my Fonts folder:
- Times New Roman Bold Italic.ttf
- Times New Roman Bold.ttf
- Times New Roman Italic.ttf
- Times New Roman.ttf
来源:https://stackoverflow.com/questions/40703932/javafx-font-derive-bold