JLabel html文本忽略setFont

Rya*_*n N 10 html java fonts swing jlabel

我刚刚开始将我的Swing应用程序从OS X移植到Windows,而且事情很痛苦JLabel.

我注意到setFont如果标签的文本是HTML ,则忽略指定的字体(这在Mac上不会发生).HTML格式对于复杂显示的可读性非常有用.

在正常情况下,我会在HTML标记中指定字体,但我使用的字体是在运行时使用Font.createFontJAR中的ttf 加载的.我尝试在字体标记中使用加载的字体名称,但这不起作用.

有什么方法可以在Windows上使用加载awt.Fonthtml-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();}
                        }
                });
        }

}
Run Code Online (Sandbox Code Playgroud)

编辑:有趣的是,如果我使用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();}
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

编辑2:此处描述的用于设置默认JLabel字体的方法具有完全相同的问题(明文显示正常,html文本没有): 更改默认JLabel字体

编辑3:我注意到即使是dafont的随机字体也会在系统上安装(即使使用这个确切的代码,我从文件中加载了[now installed] ttf的副本).

Rya*_*n N 12

registerFont()

我在谷歌搜索时找到了这个小宝石,我是否可以.ttf在运行时将其复制到JRE中.它完全符合预期.如果您Font.createFont在运行时使用加载字体,只需执行以下操作:

GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myCreatedFont)

将其注册到JRE.

这允许字体显示在HTML文本和Windows上的纯文本!