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.(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