我正在尝试设置在 jar 文件根目录下的资源文件夹中找到的字体“bilboregular.ttf”。如果我从 netbeans 运行,字体设置成功,但是如果从 jar 文件运行,则字体设置失败
代码:
main method:{
String s = System.getProperty("user.dir") + "\\src\\resources\\" + "bilboregular.ttf";
File a = new File(s);
if (a.exists()) {
this.loadFont(s);
} else {
this.loadFont(this.getClass().getResource("/resources/" + "bilboregular.ttf").getFile());
}
}
public void loadFont(String s) {
try {
font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, new File(s));
font = font.deriveFont(Font.PLAIN, 20);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
setFonts();
} catch (Exception ex) {
}
}
public boolean setFonts() {
jLabel3.setFont(font);
jLabel4.setFont(font);
return true;
}
最佳答案
你的 main 不能使用 getClass()
因为它是 static
(假设你的意思是 public static void main(String args[])
与“main”)。
试试这个代码:
InputStream is = getClass().getResourceAsStream("/resources/bilboregular.ttf");
Font f = Font.createFont(Font.TRUETYPE_FONT, is);
如果这不起作用:请发布您的 JAR 结构和抛出的异常(例如,在您的 catch
block 中使用记录器)。
顺便提一句。空的异常 block 在这里不是一个好主意,因为 IO 操作在许多情况下可能会失败。
关于java在jar文件中设置字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13732009/