【问题标题】:Java Font createFont not working (IOException)Java 字体 createFont 不起作用(IOException)
【发布时间】:2018-06-03 07:06:30
【问题描述】:

我正在尝试将我制作的自定义字体加载到摇摆的 JTable 中。 我就是这样做的:

private void carregar_font(){
    try {
        URL fontName = getClass().getResource("fonts/open.ttf");
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File(fontName.toString())));
            } catch (IOException e) {
                e.printStackTrace();
                } catch(FontFormatException e) {
        e.printStackTrace();
        }
    }

这给了我一个 IOException。有什么建议吗?谢谢

【问题讨论】:

  • 能否请您发布正确的minimal reproducible example 和确切的堆栈跟踪?
  • 你在使用 maven 吗?
  • @Mdkhirulashik,不
  • 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。

标签: java swing fonts ioexception


【解决方案1】:

getClass().getResource 返回一个 URL,而不是文件名。将其直接传递给 new File 会导致文件无效且不存在。

不保证资源 URL 指向文件。请改用 getResourceAsStream 和 other Font.createFont method

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try (InputStream fontStream = getClass().getResourceAsStream("fonts/open.ttf")) {
    ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, fontStream));
}

【讨论】:

    猜你喜欢
    • 2013-01-02
    • 2019-02-27
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多