6

I am going to use custom font in my application. For that I am using Font.createFont() method. My code is given below. It works fine when I run my main class using command

java myAppl.class

The font file is in same directory that of my class file. But when I bundled all files and font files in JAR and then run my application from JAR, the custom font do not loaded. Why?

InputStream is = this.getClass().getResourceAsStream("myfont.TTF");
uniFont=Font.createFont(Font.TRUETYPE_FONT,is);
Font f = uniFont.deriveFont(24f);

What should I do?

BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
parag
  • 61
  • 1
  • 2
  • 2
    Is the path to the font correct and it is not something like resources/fonts/myfont.TTF in the jar file? Also make sure the case is correct. – lobster1234 Apr 14 '11 at 21:02

3 Answers3

4
  1. Make sure the case of the font file name & extension is exactly the same in code as on the file system. Windows may not be case sensitive, but Java is.
  2. Check the InputStream returned by getResourceAsStream() for null. If it is null, that indicates the resources was not located.
  3. Put the font in the root of the Jar and add "/" as the prefix to the name.
Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
1

As Andrew response, I've tested exactly code above and works:

InputStream is = this.getClass().getResourceAsStream("/myfont.TTF");
uniFont=Font.createFont(Font.TRUETYPE_FONT,is);

Just missing "/" before file name. Note: jar package by Netbeans

Emerson Moretto
  • 131
  • 1
  • 3
0

Try copying the font to the jre/lib/font folder

or use the package-qualified name ("com.mypackagename.myfont.TTF")

Aleadam
  • 39,843
  • 9
  • 85
  • 108