java – JLabel html文本忽略setFont

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

我注意到,如果标签的文本是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上的明文!

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...