-1

Here I am planning to assign non-standard font(MetricWeb-BlackItalic.woff) to a JLabel. Have written below snippet and it doesn't seems to work. Its taking default font.

  String htmlText = "<html><style type=\"text/css\"> @font-face {font-family: \"MyCustomFont\";src: url('MetricWeb-BlackItalic.woff') format(\"woff\");}"+
                                      " p.customfont { font-family: \"MyCustomFont\"}</style> <p class=\"customfont\">Hello world!</p></html>";

    JLabel label = new JLabel(htmlText);
    System.out.println(htmlText+label.getFont());

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);**Output** : Default font frame - javax.swing.plaf.FontUIResource [family=Dialog,name=Dialog,style=bold,size=12]

Note: Tried with ttf, otf and woff font formats.

Can anyone help to resolve this issue ? or is there any other way to solve this problem?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3781572
  • 175
  • 1
  • 4

1 Answers1

3

Simply register the font with the graphics environment. Here is an example.

enter image description here

import java.awt.*;
import javax.swing.*;
import java.net.URL;

public class RegisterFontForHTML {

    public static final String html = "<html><body style='font-size: 20px;'>"
            + "<p>Here is some text in the default font."
            + "<p style='font-family: Airacobra Condensed;'>"
            + "Here is some text using 'Airacobra Condensed' font.";

    public static void main(String[] args) throws Exception {
        // This font is < 35Kb.
        URL fontUrl = new URL("http://www.webpagepublicity.com/"
                + "free-fonts/a/Airacobra%20Condensed.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, fontUrl.openStream());
        GraphicsEnvironment ge
                = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(font);
        // GUIs whould be started on the EDT.  BNI.
        JOptionPane.showMessageDialog(null, new JLabel(html));
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433