Java不能读取字体 [英] Java Can't Read font
问题描述
java.io.IOException:在TowerDefense中无法读取REVOLUTION.ttf
(位于java.awt.Font.createFont(未知源))
。< init>(TowerDefense.java:55)$我在TowerDefense.main(TowerDefense.java:302)
空指针异常,因为我在哪里使用字体。但我不知道为什么说它不能读取它。这是创建字体的代码:
try {
revolution = Font.createFont(Font.TRUETYPE_FONT,new文件( REVOLUTION.ttf));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(revolution);
}
catch(Exception e){
e.printStackTrace();
文件夹布局 $ b TowerDefense
$ s
默认包
TowerDefense.java
Game.java
DragTest.java
JRE系统库
REVOLUTION.ttf
neuropol.ttf
您无法使用File API访问JAR的内容。
使用Classloader的 getResourceAsStream
方法加载字体文件。为了实现这个功能,你必须把字体文件放在classpath中。
所以你的代码变成了:
<$ ()。getClassLoader()。getResourceAsStream(REVOLUTION.ttf));
如果字体包含在JAR中的包或文件夹中,则路径会相应地改变。
getResourceAsStream(com / example / font / REVOLUTION.ttf); //如果字体存在于com.example.font包中
Ok, so I have a problem using a custom font. Basically I get a custom font I downloaded off the internet and use it in my program. When I run the program in Eclipse (the editor I use), everything works fine, and there is no problem. BUT, whenever I export it to a jar from eclipse, or try to run it from the command prompt I get this very annoying error:
java.io.IOException: Can't read REVOLUTION.ttf
at java.awt.Font.createFont(Unknown Source)
at TowerDefense.<init>(TowerDefense.java:55)
at TowerDefense.main(TowerDefense.java:302)
I get that along with a bunch of null pointer exceptions because of where I use the font. But I don't know why it says it can't read it. Here is the code that creates the font:
try {
revolution = Font.createFont(Font.TRUETYPE_FONT, new File("REVOLUTION.ttf"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(revolution);
}
catch (Exception e) {
e.printStackTrace();
}
FOLDER LAYOUT
TowerDefense
src
default package
TowerDefense.java
Game.java
DragTest.java
JRE System Library
REVOLUTION.ttf
neuropol.ttf
You can not access contents of a JAR using File API.
You have to load the font file using Classloader's getResourceAsStream
method. For this to work you'll have to put the font file on classpath.
So you code becomes:
revolution = Font.createFont(Font.TRUETYPE_FONT, getClass().getClassLoader().getResourceAsStream("REVOLUTION.ttf"));
If font is included inside a package or folder in JAR, then path would change accordingly.
getResourceAsStream("com/example/font/REVOLUTION.ttf"); // if font is present inside com.example.font package
这篇关于Java不能读取字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!