JLabel html text ignores setFont

怎甘沉沦 提交于 2019-12-01 03:20:58
Ryan N

registerFont()

I found this little gem while Googling about if I could copy a .ttf into the JRE at runtime. It does exactly what it's supposed to. If you use Font.createFont to load a font at runtime, just do:

GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myCreatedFont)

to register it with the JRE.

This allows the font to show up in HTML'd text as well as plaintext on Windows!

For reference, here's what is seen on Mac OS X.

By comparison, here's the display on Ubuntu 10, OpenJDK 6.

import java.awt.Font;
import java.awt.GridLayout;
import java.io.File;
import javax.swing.*;

public class LabelTestFrame extends JFrame {

    public LabelTestFrame() throws Exception {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(0, 1));
        String fontPath = "SophomoreYearbook.ttf";
        Font testFont = Font.createFont(
            Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f);
        JLabel label1 = new JLabel("<html>Some HTML'd text</html>");
        label1.setFont(testFont);
        this.add(label1);
        JLabel label2 = new JLabel("Some plaintext");
        this.add(label2);
        this.pack();
        this.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new LabelTestFrame().setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!