我在 Swing JToolBar 的按钮中显示 FontAwesome 集合中的某些字形时遇到问题。这是一个截图来说明(请注意,右侧工具栏中的顶部按钮不是一个漂亮的图标,而是显示三个空矩形):
重现这个的代码(至少在我的 Mac 上)是:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;![enter image description here][2]
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
public class TestFontAwesome {
public static void main(String[] args) {
new TestFontAwesome();
}
public TestFontAwesome() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try (InputStream is = TestFontAwesome.class.getResourceAsStream("/fontawesome-webfont_old.ttf")) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
font = font.deriveFont(Font.PLAIN, 24f);
JToolBar toolBar = new JToolBar(JToolBar.VERTICAL);
JButton button1 = new JButton("\uf00e");
button1.setFont(font);
toolBar.add(button1);
JButton button2 = new JButton("\uf01e");
button2.setFont(font);
toolBar.add(button2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JButton("Irrelevant content..."));
frame.add(toolBar, BorderLayout.EAST);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException | FontFormatException exp) {
exp.printStackTrace();
}
}
});
}
}
我尝试了几件事:(1)使用不同版本的FontAwesome.ttf文件,没有变化;(2) 尝试不同的JDK版本,没有变化;(3) 在常规 JButton 中显示相同的字符,这可以在以下屏幕截图中看到(因此这显然不是字体文件的问题):
我在非 Retina Mac 上进行了测试,一切正常,所以我想知道这是否是 Retina 显示器特有的东西。如果有人有任何建议,我会很高兴收到您的来信,谢谢。
仅 JButton 示例的代码(工作正常)是:
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TestFontAwesome2 {
public static void main(String[] args) {
new TestFontAwesome2();
}
public TestFontAwesome2() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try (InputStream is = TestFontAwesome.class.getResourceAsStream("/fontawesome-webfont_old.ttf")) {
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
font = font.deriveFont(Font.PLAIN, 24f);
JButton button1 = new JButton("\uf00e");
button1.setFont(font);
JButton button2 = new JButton("\uf01e");
button2.setFont(font);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new JButton("Irrelevant content..."));
frame.add(button1);
frame.add(button2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException | FontFormatException exp) {
exp.printStackTrace();
}
}
});
}
}