java label 字体,Java Swing JLabel,HTML和自定义字体

In our Java Swing application, we're loading a custom font and adding it to a JLabel:

try {

this.font = Font.createFont(Font.TRUETYPE_FONT, new File("resources/fonts/ourcoolfont.ttf")).deriveFont(16f);

} catch (Exception e) {

this.font = new Font("Arial", Font.PLAIN, 16);

}

this.label.setFont(this.font);

Easy and worked fine on 3 different systems. Until someone else tried to run it. The font was loaded (as we're also using on some other Swing elements), but not used in the JLabel.

After some searching, I've found out you can't use both HTML and a loaded font. For some reasons it works on my system (I assume it has something to do with the Java version), but not on some others. As we would like the project to work in outdated Java versions, just asking to update isn't an option.

One option is to install the font on the computer, something we don't like to do. The best solution I've found is this one:

How can I create a Java/Swing text component that is both styled and has a custom font?

However, that question is about a JTextPane. A JLabel doesn't seem to have a getStyledDocument() method I can use for that.

Is there any way to let our font work with the JLabel?

解决方案

To use some font:

...

The Font you created has to be registered first in the singleton GraphicsEnvironment to be accessible to all:

GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();

genv.registerFont(font);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值