我目前正在使用这种代码为我的应用程序加载资源。例如:
public class MyResources {
private static final String FONT_FILE = "path/to/resource";
private static Font font;
static {
try (InputStream is = MyResources.class.getResourceAsStream(FONT_FILE)) {
font = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.PLAIN, 15f);
} catch (IOException | FontFormatException e) {
System.err.println("Could not load font: " + FONT_FILE);
}
// .....
// other resources here
// .....
}
public static Font getFont() {
return font;
}
}
然后我使用我想要的任何类的字体:
label.setFont(MyResources.getFont());
从静态初始化程序中加载资源(字体,图像等)是一个好习惯吗?一般来说,在Swing应用程序中加载资源(将在不同类中多次使用)的最佳实践是什么?