Launching the jar, the console says that the file is not found and the font is not loaded. How could I solve this problem?
I got this code:
public class FontLoader {
public static Font load(){
String fontFilePath = Paths.get(System.getProperty("user.dir"), "prova.jar", "Retro Gaming.ttf").toString();
int fontStyle = Font.BOLD;
int fontSize = CenterOnDefaultScreen.center().height*2/100;
Font font = null;
int fontTypeResource = Font.TRUETYPE_FONT;
if((fontFilePath == null || fontFilePath.isEmpty()) || fontSize < 1) {
throw new IllegalArgumentException("load() Method Error! Arguments "
"passed to this method must contain a file path or a numerical "
"value other than 0!" System.lineSeparator());
}
try {
font = Font.createFont(fontTypeResource, new FileInputStream(
new File(fontFilePath))).deriveFont(fontStyle, fontSize);
}
catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException: " fontFilePath);
}
catch (FontFormatException | IOException ex) {
System.out.println("Exception thrown");
}
return font;
}
}
CodePudding user response:
String fontFilePath = Paths.get(System.getProperty("user.dir"), "prova.jar", "Retro Gaming.ttf").toString();
That.. rather obviously won't work.
You need to use the gRAS (getResourceAsStream) system. File
in java (as in, what new FileInputStream
needs, the java.io.File
object) are actual files. entries inside jar files don't count. It is not possible to refer to that ttf file with a File
object, nor to open it with FileInputStream.
Fortunately, the createFont
method doesn't demand that you pass a FileInputStream
; any old InputStream
will do.
The ttf file needs to be in the same classpath root as the this very class you are writing (for example, the same jar). Once you've ensured that is the case, you can use gRAS:
try (var fontIn = FontLoader.class.getResourceAsStream("/Retro Gaming.ttf")) {
Font.createFont(Font.TRUETYPE_FONT, fontIn).deriveFont(.., ...);
}
gRAS looks in the same place as where FontLoader.class
lives. From your snippet it sounds like you put the ttf in the 'root' of the jar and not next to FontLoader. The leading slash in the string argument to getResourceAsStream
means: Look relative to the root of the place FontLoader is in (so, your jar, presumably).