Adding fonts to Swing application and include in package

爱⌒轻易说出口 提交于 2019-12-03 10:41:48

You could load them via an InputStream:

InputStream is = MyClass.class.getResourceAsStream("TestFont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);

This loaded font has no predefined font settings so to use, you would have to do:

Font sizedFont = font.deriveFont(12f);
myLabel.setFont(sizedFont);

See:

Physical and Logical Fonts

As Reimeus said, you can use an InputStream. You can also use a File:

File font_file = new File("TestFont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, font_file);

In both cases you would put your font files in either the root directory of your project or some sub-directory. The root directory should probably be the directory your program is run from. For example, if you have a directory structure like:

My_Program
|
|-Fonts
| |-TestFont.ttf
|-bin
  |-prog.class

you would run your program with from the My_Program directory with java bin/prog. Then in your code the file path and name to pass to either the InputStream or File would be "Fonts/TestFont.ttf".

Ahmad R. Nazemi

Try this:

@Override
public Font getFont() {
    try {
        InputStream is = GUI.class.getResourceAsStream("TestFont.ttf");
        Font font = Font.createFont(Font.TRUETYPE_FONT, is);
        return font;
    } catch (FontFormatException | IOException ex) {
        Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        return super.getFont();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!