简体   繁体   中英

How to load Fonts from a jar?

I am using java.awt.Frame for my Java application window which is being refreshed from a loop inside main.

The application behaves exactly as it should when it is run from Eclipse, but when I package it into a jar, It draws the first screen, but then nothing else after that.

when I try switching the window to a JFrame, it works, but only a portion of the images get drawn and updated.

I'm not sure what the problem is? If it runs fine from eclipse, shouldn't it run the exact same in a jar file?

EDIT: I figured out the problem. Its due to fonts not loading from the jar file. Is there a way to get these to load correctly? This is my code for them:

Font font = Font.createFont(Font.TRUETYPE_FONT, 
  obj.getClass().getClassLoader().getResource(fontName));

获取指向它的URL,然后查看此答案以创建它并在可用字体中注册它。

Try this code for loading font files from within a .jar file.

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.net.URISyntaxException;

public class FontLoader
{
    private ResourceLoader loader;

    public FontLoader(String fontFilePath)
    {
        loader = new ResourceLoader(fontFilePath);
    }

    public Font getFont(int fontStyle, float fontSize) throws FontFormatException, IOException, URISyntaxException
    {
        Font font = Font.createFont(Font.TRUETYPE_FONT, loader.getResource());

        font = font.deriveFont(fontStyle, fontSize);

        return font;
    }
}

Note that you also need my ResourceLoader class which you can find here:
How do I load a file from resource folder?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM