问题描述
我正在尝试将自定义字体添加到我的jswing应用程序中,但是我找不到如何正确上传.ttf文件的方法,以便一旦创建可执行jar文件就可以使用它。
问题在这里,新File(getClass()。getResourceAsStream(“ /” +“ cs_regular.ttf”))
谢谢!
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT,new File(getClass().getResourceAsStream("/"+"cs_regular.ttf"))));
} catch (FontFormatException|IOException e) {
pr("Error_107");
}
解决方法
从流中创建java.io.File
并非易事,您可以直接从流中创建字体。
看这个答案。
https://stackoverflow.com/a/40862139/10999348
这是我现在的工作代码
InputStream stream =ClassLoader.getSystemClassLoader().getResourceAsStream("cs_regular.ttf");
try {
csfont = Font.createFont(Font.TRUETYPE_FONT,stream).deriveFont(48f);
} catch (FontFormatException|IOException e) {
//handle exeption
}
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(csfont);