【发布时间】:2019-02-27 12:42:18
【问题描述】:
我正在为一个班级编写的国际象棋程序实现一个 GUI。为了让它看起来更漂亮,我想使用从互联网上获得的 Chess Piece Font。
文件 chess.ttf 位于路径 Chess/resources/chess.ttf。我根据 Oracle 的指令 (https://docs.oracle.com/javase/tutorial/2d/text/fonts.html) 使用以下代码:
try {
File file = new File("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, file));
//Derive and return a 12 pt version:
//Need to use float otherwise
//it would be interpreted as style
return font.deriveFont(12f);
}
catch (IOException|FontFormatException e) {
System.out.println("-Font Error-");
return null;
}
但是,这会引发 IOException。我在文件上运行 getAbsolutePath() 并收到 /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf 所以我假设文件正在正确加载。有谁知道我的代码出了什么问题?
编辑:问题解决了吗?我按照建议尝试了 InputStreams,但没有奏效,但在恢复我的代码后,计算机终于停止抛出 IOExceptions。代码不是最好的吗?
【问题讨论】:
-
尝试使用
Class#getResource或Class#getResourceAsStream。 “我在文件上运行 getAbsolutePath() 并收到 /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf 所以我假设文件” -File是“抽象”表示,不能保证File实际存在于指定位置 - 为此使用exists -
扩展@MadProgrammer 评论的前面部分。应用程序资源将在部署时成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。
标签: java fonts awt embedded-resource ioexception