【发布时间】:2013-10-07 22:15:39
【问题描述】:
大家好,我在将自定义字体加载到 Java 时遇到了一些问题。
public class CustomFonts extends JPanel {
public static void loadFont() throws FontFormatException, IOException {
String fontFileName = "stocky.ttf";
InputStream is = CustomFonts.class.getClassLoader()
.getResourceAsStream(fontFileName);
Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, is);
Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
ge.registerFont(ttfReal);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Blach Blach Blach");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
loadFont();
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JLabel fontF = new JLabel("Testing 1, 2, 3");
fontF.setFont(new Font("ttfReal", Font.PLAIN, 20));
frame.add(fontF);
}
}
当我运行代码时,字体似乎是默认字体。我已将 ttf 文件加载到 Eclipse 的项目文件夹中,但我是否必须给出该文件的显式路由? 我试图通过这个基本程序来理解字体,因为我试图将它加载到一个更大的程序中。
【问题讨论】:
-
您的自定义字体设置不正确,因为找不到名为
ttfReal的字体。registerFont不会通过 Font 对象的局部变量名称来命名字体。您可以通过listing all font names 确定自定义字体的名称,但您可能会发现将自定义字体简单地存储在一个类变量中并在需要设置它的版本时从它派生出来更容易。
标签: java swing fonts awt embedded-resource