Search code examples
javajarjava-font

Content from Jar file


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?


Solution

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