Content from Jar file

191 Views Asked by At

Is it possible to create a custom font with a .ttf file that is inside a .jar file? I've created a jar file with the following structure

Game.jar
├──Snake  
│  ├── lib  
│  |   └── game_over.ttf  
|  ├── src  
│  |   ├── GameFrame.class  
│  |   ├── GamePanel.class  
│  |   └── SnakeGame.class

I've tried to get the custom font by doing

Font GAMEOVER_FONT;
InputStream is = this.getClass().getClassLoader().getResourceAsStream("Snake/lib/game_over.ttf");

GAMEOVER_FONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(200f);   
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, is));
g.setFont(GAMEOVER_FONT);

What am I doing wrong? Is it even possible to achieve what I'm trying?

2

There are 2 best solutions below

7
jccampanero On BEST ANSWER

Please, although I think in your use case the result should be the same, try:

this.getClass().getResourceAsStream()

Instead of:

this.getClass().getClassLoader().getResourceAsStream()

Note the difference in getClassLoader().

Perhaps there is some difference in the class loader hierarchy and it can provide you different outputs.

In addition, you can try placing the font in your classes, your Java output directory, and read it from there, in order to check if there is an actual problem with the font or not.

4
cello On

1: Use an absolute path to access the font-resource, like this:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("/Snake/lib/game_over.ttf");

Note the / before Snake.

If you don't use an absolute name, I think Java will search in the package of the class, and not at the root level of the Jar.

2: You are using the InputStream twice, as you actually call Font.createFont(...) twice. At least the second time, the input stream will either be closed or at the end, where nothing else can be read, so the second invocation will fail. Just use the loaded font for registering it:

GAMEOVER_FONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(200f);   
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(GAMEOVER_FONT); // <-- do not load 2nd time
g.setFont(GAMEOVER_FONT);