我注意到,如果标签的文本是HTML(Mac上不会发生这种情况),则将忽略指定给setFont的字体. HTML格式对复杂显示器的可读性非常有用.
在正常情况下,我会在HTML标签中指定字体,但是我使用的字体在运行时使用Font.createFont加载到JAR中的ttf.我尝试在字体标签中使用加载的字体的名称,但这没有工作.
有什么办法可以使用一个加载的awt.Font与Windows上的html-ified JLabel?
这是一个例子.我不能分享我的应用程序的字体,但我只是运行它与这一个(一个纯TTF),同样的行为发生:
http://www.dafont.com/sophomore-yearbook.font
import java.awt.Font; import java.io.File; import javax.swing.*; public class LabelTestFrame extends JFrame { public LabelTestFrame() throws Exception { boolean useHtml = true; String fontPath = "C:\\test\\test_font.ttf"; JLabel testLabel = new JLabel(); Font testFont = Font.createFont(Font.TRUETYPE_FONT,new File(fontPath)).deriveFont(18f); testLabel.setFont(testFont); if (useHtml) testLabel.setText("<html>Some HTML'd text</html>"); else testLabel.setText("Some plaintext"); getContentPane().add(testLabel); setSize(300,300); } public static void main(String[] args) { SwingUtilities.invokelater(new Runnable() { @Override public void run() { try {new LabelTestFrame().setVisible(true);} catch (Exception e) {e.printstacktrace();} } }); } }
编辑:有趣的是,如果我使用JRE的lib / fonts文件夹中的其中一个ttf(在这种情况下,一个Lucida字体在这里重命名为test_java.ttf),这个代码段将生成与布尔值相同的结果.
public LabelTestFrame() throws Exception { boolean useHtml = false; String fontPath = "C:\\test\\test_java.ttf"; JLabel testLabel = new JLabel(); Font testFont = Font.createFont(Font.TRUETYPE_FONT,new File(fontPath)).deriveFont(18f); testLabel.setFont(testFont); if (useHtml) testLabel.setText("<html><b>Some HTML'd text</b></html>"); else testLabel.setText("Some plaintext"); getContentPane().add(testLabel); setSize(300,300); } public static void main(String[] args) { SwingUtilities.invokelater(new Runnable() { @Override public void run() { try {new LabelTestFrame().setVisible(true);} catch (Exception e) {e.printstacktrace();} } }); }
编辑2:这里描述的设置默认JLabel字体的方法是完全相同的问题(明文显示,html’d文本没有):Changing default JLabel font
编辑3:我注意到,即使在系统上安装了dafont的随机字体(即使是这个确切的代码,我从一个文件中加载了一个[现在安装的] ttf的副本).
解决方法
registerFont()
我发现这个小宝石,而谷歌关于如果我可以在运行时将.ttf复制到JRE.它确实是它应该的.如果您在运行时使用Font.createFont加载字体,请执行以下操作:
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myCreatedFont)
注册JRE.
这样可以在HTML文本中显示字体以及Windows上的明文!
原文地址:https://www.jb51.cc/java/123139.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。