Adding fonts to Swing application and include in package

耗尽温柔 提交于 2019-12-04 16:51:04

问题


I need to use custom fonts (ttf) in my Java Swing application. How do I add them to my package and use them?

Mean while, I just install them in windows and then I use them, but I don't wish that the usage of the application will be so complicated, it`s not very convenient to tell the user to install fonts before using my application.


回答1:


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




回答2:


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".




回答3:


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();
    }
}


来源:https://stackoverflow.com/questions/12998604/adding-fonts-to-swing-application-and-include-in-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!