JavaFX Fonts

104 篇文章 5 订阅

The JavaFX Font class, java.scene.text.Font, enables you to load different Fonts for use in your JavaFX applications. A font is a text style. All text rendered with the same font will look similar. In this JavaFX Font tutorial I will show you how to load and set fonts in JavaFX.

Create Font Instance

To use fonts in JavaFX you must create a JavaFX Font instance. The easiest way to create a JavaFX Font instance is to use the static factory methods in the Font class. The following example shows how to create JavaFX Font instances using the many variations of the Font class static factory methods:

String      fontFamily  = "Arial";
double      fontSize    = 13;
FontWeight  fontWeight  = FontWeight.BOLD;
FontPosture fontPosture = FontPosture.ITALIC;

Font font1 = Font.font(fontFamily);
Font font2 = Font.font(fontSize);
Font font3 = Font.font(fontFamily, fontSize);
Font font4 = Font.font(fontFamily, fontWeight , fontSize);
Font font5 = Font.font(fontFamily, fontPosture, fontSize);
Font font6 = Font.font(fontFamily, fontWeight , fontPosture, fontSize);

As you can see, the Font factory methods enable you to create Font instances representing different font families, font sizes, font weights and font postures.

Using the Font Instance

Once you have created a JavaFX Font instance you use it by setting it on whatever JavaFX component capable of using a Font. For instance, you can set it on a JavaFX Text control. Here is an example of setting a Font instance on a Text control:

Font font = Font.font("Arial");

Text text = new Text("This is the text");
text.setFont(font);

Precisely how a Font object is applied to a given JavaFX control depends on the specific JavaFX control. In the JavaFX Text example the Font object is applied via the Text setFont() method, as shown above.

List Installed Font Families and Names

The JavaFX Font class provides two methods that can list the font families and font names and installed on the system the JavaFX application is running on. These methods are the getFamilies() and getFontNames() methods. Here are some examples of calling these methods:

List<String> fontFamilies = Font.getFamilies();
List<String> fontNames    = Font.getFontNames();

Both font family names and font names can be used when creating a Font instance. Provide either the font family name or font name in the Font factory method fontFamily parameter.

To see the actual names, loop through the lists above and print out their names, like this:

for(String item : fontFamilies) {
    System.out.println(item);
}
for(String item : fontNames) {
    System.out.println(item);
}

url:JavaFX Fonts

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值