我刚刚开始将我的Swing应用程序从OS X移植到
Windows,而且JLabels很痛苦.
我注意到,如果标签的文本是HTML(Mac上不会发生这种情况),则将忽略指定给setFont的字体. HTML格式对复杂显示器的可读性非常有用.
在正常情况下,我会在HTML标签中指定字体,但是我使用的字体在运行时使用Font.createFont加载到JAR中的ttf.我尝试在字体标签中使用加载的字体的名称,但这没有工作.
有什么办法可以使用一个加载的awt.Font与Windows上的html-ified JLabel?
这是一个例子.我不能分享我的应用程序的字体,但我只是运行它与这一个(一个纯TTF),同样的行为发生:
import java.awt.Font;
import java.io.File;
import javax.swing.*;
public class LabelTestFrame extends JFrame {
public LabelTestFrame() throws Exception {
boolean useHtml = true;
String fontPath = "C:\\test\\test_font.ttf";
JLabel testLabel = new JLabel();
Font testFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f);
testLabel.setFont(testFont);
if (useHtml) testLabel.setText("Some HTML'd text");
else testLabel.setText("Some plaintext");
getContentPane().add(testLabel);
setSize(300,300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {new LabelTestFrame().setVisible(true);}
catch (Exception e) {e.printStackTrace();}
}
});
}
}
编辑:有趣的是,如果我使用JRE的lib / fonts文件夹中的其中一个ttf(在这种情况下,一个Lucida字体在这里重命名为test_java.ttf),这个代码段将生成与布尔值相同的结果.
public LabelTestFrame() throws Exception {
boolean useHtml = false;
String fontPath = "C:\\test\\test_java.ttf";
JLabel testLabel = new JLabel();
Font testFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f);
testLabel.setFont(testFont);
if (useHtml) testLabel.setText("Some HTML'd text");
else testLabel.setText("Some plaintext");
getContentPane().add(testLabel);
setSize(300,300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {new LabelTestFrame().setVisible(true);}
catch (Exception e) {e.printStackTrace();}
}
});
}
编辑2:这里描述的设置默认JLabel字体的方法是完全相同的问题(明文显示,html’d文本没有):Changing default JLabel font
编辑3:我注意到,即使在系统上安装了dafont的随机字体(即使是这个确切的代码,我从一个文件中加载了一个[现在安装的] ttf的副本).