【问题标题】:Loading Custom Fonts Into Java [duplicate]将自定义字体加载到 Java 中 [重复]
【发布时间】: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


【解决方案1】:

也许设置一个静态类变量。

public class CustomFonts extends JPanel {
    private static Font ttfBase;
}

然后,当您加载字体时,将其加载到ttfBase。然后在你的主要,

public static void main (String [] args) {
    ...
    Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 20);
    fontF.setFont(ttfReal);
    ...
}

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 2012-08-08
    • 2016-06-06
    • 2014-02-08
    • 2015-05-31
    • 2018-02-23
    • 2011-11-06
    • 2014-01-27
    • 2018-08-09
    相关资源
    最近更新 更多