我正在为一个班级写的象棋程序实现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,因此我假设文件已正确加载。有人知道我的代码出了什么问题吗?
edit:问题已解决?我按照建议的方式尝试了InputStreams,但是没有用,但是在恢复我的代码后,计算机终于停止抛出IOExceptions了。代码不是最好的吗?
答案 0 :(得分:0)
您最好使用ant或maven等构建脚本复制ttf / Users / [me] / eclipse-workspace / Chess / bin / resources
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.out.println(loader.getResource(".").getPath()); // for tracing the working folder only
java.io.InputStream ins = loader.getResourceAsStream("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, ins);