java_swing相关知识总结
使用自定义字体
使用
URL
+File
。(个人推荐使用这一种)1
2
3
4
5
6
7
8
9
10
11
12
13private 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
临时文件)1
2
3
4
5
6
7
8
9
10
11private 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;
}全局字体设置
1
2
3
4
5
6
7
8
9
10private 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);
}
}
}