简体   繁体   English

Java Swing JLabel,HTML和自定义字体

[英]Java Swing JLabel, HTML and custom fonts

In our Java Swing application, we're loading a custom font and adding it to a JLabel : 在我们的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);

Easy and worked fine on 3 different systems. 在3种不同的系统上轻松完美。 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 . 字体已加载(因为我们也在其他一些Swing元素上使用),但未在JLabel

After some searching, I've found out you can't use both HTML and a loaded font. 经过一番搜索,我发现你不能同时使用HTML和加载的字体。 For some reasons it works on my system (I assume it has something to do with the Java version), but not on some others. 由于某些原因,它适用于我的系统(我认为它与Java版本有关),但不适用于其他一些系统。 As we would like the project to work in outdated Java versions, just asking to update isn't an option. 由于我们希望项目在过时的Java版本中工作,因此只是要求更新不是一种选择。

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? 我发现的最佳解决方案是: 如何创建既有样式又有自定义字体的Java / Swing文本组件?

However, that question is about a JTextPane . 但是,这个问题是关于JTextPane A JLabel doesn't seem to have a getStyledDocument() method I can use for that. JLabel似乎没有我可以使用的getStyledDocument()方法。

Is there any way to let our font work with the JLabel ? 有没有办法让我们的字体与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中注册才能被所有人访问:

GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
genv.registerFont(font);

因为StyledDocument扩展了Document ,所以您可以使用JTextFieldsetDocument()方法来实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM