这里我打算将非标准字体(MetricWeb-BlackItalic.woff)分配给JLabel。写下面的片段,它似乎不起作用。它采用默认字体。
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]
注意:尝试使用ttf,otf和woff字体格式。
任何人都可以帮忙解决此问题吗?或者还有其他方法可以解决这个问题吗?
答案 0 :(得分:2)
只需在图形环境中注册字体即可。这是一个例子。
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));
}
}