JLabel html text ignores setFont

前端 未结 2 967
闹比i
闹比i 2021-01-04 19:00

I\'ve just started porting my Swing app from OS X to Windows and things are painful with JLabels.

I\'ve noticed that the font specified to setFont

相关标签:
2条回答
  • 2021-01-04 19:19

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

    enter image description here

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

    enter image description here

    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();
                    }
                }
            });
        }
    }
    
    0 讨论(0)
  • 2021-01-04 19:39

    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!

    0 讨论(0)
提交回复
热议问题