简体   繁体   English

将字体添加到Swing应用程序并包含在包中

[英]Adding fonts to Swing application and include in package

I need to use custom fonts (ttf) in my Java Swing application. 我需要在Java Swing应用程序中使用自定义字体(ttf)。 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. 同时,我只是在Windows中安装它们然后我使用它们,但我不希望应用程序的使用会如此复杂,在使用我的应用程序之前告诉用户安装字体并不是很方便。

You could load them via an InputStream : 您可以通过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 . 正如Reimeus所说,你可以使用InputStream You can also use a File : 您还可以使用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 . 你可以使用java bin/progMy_Program目录运行你的程序。 Then in your code the file path and name to pass to either the InputStream or File would be "Fonts/TestFont.ttf" . 然后在您的代码中,传递给InputStreamFile的文件路径和名称将是"Fonts/TestFont.ttf"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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