Java 将非标准字体指定给JLabel
在这里,我计划将非标准字体(MetricWeb BlackItalic.woff)分配给JLabel。我写了下面的代码片段,但它似乎不起作用。它采用默认字体Java 将非标准字体指定给JLabel,java,html,swing,fonts,jlabel,Java,Html,Swing,Fonts,Jlabel,在这里,我计划将非标准字体(MetricWeb BlackItalic.woff)分配给JLabel。我写了下面的代码片段,但它似乎不起作用。它采用默认字体 String htmlText = "<html><style type=\"text/css\"> @font-face {font-family: \"MyCustomFont\";src: url('MetricWeb-BlackItalic.woff') format(\"woff\");}"+
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]
String htmlText=“@font-face{font-family:\'MyCustomFont\'src:url('MetricWeb-BlackItalic.woff')格式(\'woff\”);”+
“p.customfont{font family:\'MyCustomFont\'”}你好,世界!
”;
JLabel标签=新的JLabel(htmlText);
System.out.println(htmlText+label.getFont());
JFrame=新JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(标签);
frame.pack();
frame.setVisible(true)**输出**:默认字体框架-javax.swing.plaf.FontUIResource[family=Dialog,name=Dialog,style=bold,size=12]
注意:尝试使用ttf、otf和woff字体格式
有人能帮助解决这个问题吗?或者有其他方法解决这个问题吗?只需在图形环境中注册字体即可。这里有一个例子
import java.awt.*;
导入javax.swing.*;
导入java.net.URL;
公共类RegisterFontForHTML{
公共静态最终字符串html=“”
+“这里有一些默认字体的文本。”
+“”
+“以下是一些使用“Airacobra Condensed”字体的文本。”;
公共静态void main(字符串[]args)引发异常{
//此字体小于35Kb。
URL fontUrl=新URL(“http://www.webpagepublicity.com/"
+“免费字体/a/Airacobra%20Condensed.ttf”);
Font Font=Font.createFont(Font.TRUETYPE_Font,fontUrl.openStream());
图形环境
=GraphicsEnvironment.getLocalGraphicsEnvironment();
注册方(字体);
//将在EDT.BNI上启动GUI。
showMessageDialog(null,新JLabel(html));
}
}
可能。
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));
}
}