java 将字体添加到 Swing 应用程序并包含在包中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12998604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding fonts to Swing application and include in package
提问by DanM
I need to use custom fonts (ttf) in my Java Swing application. How do I add them to my package and use them?
我需要在 Java Swing 应用程序中使用自定义字体 (ttf)。如何将它们添加到我的包中并使用它们?
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中安装它们然后我使用它们,但我不希望应用程序的使用如此复杂,在使用我的应用程序之前告诉用户安装字体不是很方便。
回答by Reimeus
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:
看:
回答by Mr. Zurg
As Reimeus said, you can use an InputStream
. You can also use a File
:
正如 Reimeus 所说,您可以使用InputStream
. 您还可以使用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"
.
您将从My_Program
目录中运行您的程序java bin/prog
。然后在您的代码中,要传递给InputStream
或的文件路径和名称File
将是"Fonts/TestFont.ttf"
.
回答by 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();
}
}