javaswingfontsjframecustom-font

Java cannot read font.ttf


I am trying to make a game in Java using JFrame, and am working on a title screen. For my title, I am attempting to use a custom font that I downloaded, and have kept in my file hierarchy named "titleFont.ttf". However, when using the code (below), I keep getting the following error.

In Main.java:

public class Main {

    public static void main(String[] args) {
        
        Setup.loadFont("assets/titleFont.ttf");
        
        // Create the window
        new AppWindow(Setup.window, Setup.width, Setup.height, Setup.content, Setup.titlePanel);
        System.out.println("Window running...");

    }

}

In Setup.java:

public static Font loadFont(String path) {

    
    try {
        
        InputStream fileStream = Font.class.getResourceAsStream(path);
        Font myFont = Font.createFont(Font.TRUETYPE_FONT, fileStream);
        return myFont.deriveFont(Font.PLAIN, 12f);
        
    } catch (FontFormatException | IOException e) { e.printStackTrace(); }
    
    return null;
    
}

java.io.IOException: Problem reading font data.
at java.desktop/java.awt.Font.createFont0(Font.java:1183)
at java.desktop/java.awt.Font.createFont(Font.java:1052)
at engine.Main.loadFont(Main.java:25)
at engine.Main.main(Main.java:12)

Here is my file setup:

file setup

Can someone please let me know what I need to fix, and how? Thank you in advance! Also, does this mean I am only loading the font, and not setting it to be used? If so, how do I set the font so that the text written on the screen is in that custom font style?

P.S. I'm new to this, so please try to explain this as you would with no experience. Sorry!


Solution

  • The File(String) constructor treats it's parameter as a relative path (relative to the "current" directory).

    So you'd probably want to specify either an absolute path (starting with a '/'), or an actual relative path to the file from the place that the application was started from.

    Probably the better way to do this is to use a Stream (instead of a File), created from a Resource in the classpath.

    For an example, see the accepted answer to Cant add custom font with using .getResource() - Java