使用前需要在resources内配置好字体文件,并在相关的properties配置对应路径。
- 使用URL+File。(个人推荐使用这一种)
private static Font getCustomFont(String fontPath, int style, int size) {
try {
URL url = CustomFont.class.getResource(fontPath);
File fontFile = new File(url.getFile());
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
return font.deriveFont(style, size);
} catch (IOException e) {
System.out.println(e.getMessage() + ": 无法读取文件" + fontPath);
} catch (FontFormatException e) {
throw new RuntimeException(e);
}
return null;
}
- 使用getResourceAsStream。(会产生.tmp临时文件)
private static Font getCustomFont2(String fontPath, int style, int size) {
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, CustomFont.class.getResourceAsStream(fontPath));
return font.deriveFont(style, size);
} catch (IOException e) {
System.out.println(e.getMessage() + ": 无法读取文件" + fontPath);
} catch (FontFormatException e) {
throw new RuntimeException(e);
}
return null;
}
- 全局字体设置
private static void initGlobalFont(Font font) {
FontUIResource fontRes = new FontUIResource(font);
for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
Object key = keys.nextElement();
Object value = UIManager.get(key);
if (value instanceof FontUIResource) {
UIManager.put(key, fontRes);
}
}
}