Java字体createFont无法正常工作(IOException)

问题描述 投票:0回答:1

我正在尝试将我制作的自定义字体加载到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。有什么建议吗?谢谢

java swing fonts ioexception
1个回答
0
投票

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));
}
© www.soinside.com 2019 - 2024. All rights reserved.