Java Swing JLabel,HTML和自定义字体 [英] Java Swing JLabel, HTML and custom fonts
问题描述
在我们的Java Swing应用程序中,我们加载了一个自定义字体并将其添加到 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);
在3种不同的系统上工作得很好。直到有人试图运行它。字体被加载(因为我们也在使用一些其他的Swing元素),但没有在 JLabel
中使用。
经过一番搜索之后,我发现你不能同时使用HTML和加载的字体。由于某些原因,它在我的系统上工作(我认为它与Java版本有关),但不是其他的。因为我们希望项目能够在过时的Java版本中工作,所以只是要求更新不是一个选项。
一种选择是在电脑上安装字体,我们不喜欢这样做。我发现的最好的解决方案是这样的:
然而,这个问题是关于一个 JTextPane
。 JLabel
似乎没有一个 getStyledDocument()
方法,我可以使用它。
有没有什么办法可以让我们的字体和 JLabel
?
< html>< head>< html>< style type =text / css>
body {font-family:Cool; < / head>< body> ...
创建必须首先在单一GraphicsEnvironment中注册,以便所有人都可以访问:
GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);
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:
<html><head><style type="text/css">
body { font-family: Cool; } </style></head><body>...
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);
这篇关于Java Swing JLabel,HTML和自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!