Access custom font from Jar

I am going to use my own font in my application. For this, I use the Font.createFont() method. My code is below. It works great when I run my main class with the command

java myAppl.class

The font file is in the same directory as in my class file. But when I linked all the files and font files in the JAR and then launched the application from the JAR, the custom font did not load. Why?

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

What should I do?

+6
source share
3 answers
  • Make sure the file name and font extension exactly match the code in the file system. Windows may not be case sensitive, but Java is.
  • Check the InputStream returned by getResourceAsStream() for null . If it is null , this indicates that the resources were not located.
  • Put the font in the root of the Jar and add "/" as a prefix to the name.
+4
source

As Andrew's answer, I checked the exact code above and it works:

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

There is simply no "/" in front of the file name. Note: Netbeans jar package

+1
source

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

or use the name assigned to the packages ("com.mypackagename.myfont.TTF")

0
source

Source: https://habr.com/ru/post/885941/


All Articles