Search code examples
javaswingfontsembedded-resource

Java - How to Load a Custom Font From a Resources Folder


I'm using java swing to create an app, but I'm also stuck trying to load some font! Here is the problem: I Have a resource folder with some custom font, when I try to load them using this code:

    public static Font CustomFont(String path) {
        Font customFont = loadFont(path, 24f);
        System.out.println(customFont == null);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(customFont);
        return customFont;

    }
    public static Font loadFont(String path, float size){
        try {
            Font myFont = Font.createFont(Font.TRUETYPE_FONT, Launcher.class.getResourceAsStream(path));
            return myFont.deriveFont(Font.PLAIN, size);
        } catch (FontFormatException | IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }

UiFonts.java

    public static Font Nunito;

    public static void init() {
        Nunito = CustomFont("Fonts/Nunito/Nunito-BlackItalic.ttf");
    }

This is my resource folder: My project file and folder

It always show me error depending on the path.

Example: Cant read font file data.

Solution

I needed to add / before the Font like this:

Nunito = CustomFont("/Fonts/Nunito/Nunito-BlackItalic.ttf");

Also my resources folder wasn't in my java folder. Now it look like this: Solution project file and code


Solution

  • You may want to have a read on Accessing Resources in Java.

    You need leading / denotes the root of your class path as well as the resource package name.

    Nunito = CustomFont("/resources/Fonts/Nunito/Nunito-BlackItalic.ttf");
    

    With that being said I can't tell where you class is, it's weird your resources folder/package is separate from your java usually they would be in the same folder just in a different package.