大家好,我在将自定义字体加载到Java时遇到了一些麻烦。
public class CustomFonts extends JPanel {
public static void loadFont() throws FontFormatException, IOException {
String fontFileName = "stocky.ttf";
InputStream is = CustomFonts.class.getClassLoader()
.getResourceAsStream(fontFileName);
Font ttfBase = Font.createFont(Font.TRUETYPE_FONT, is);
Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
ge.registerFont(ttfReal);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Blach Blach Blach");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try {
loadFont();
} catch (FontFormatException | IOException e) {
e.printStackTrace();
}
JLabel fontF = new JLabel("Testing 1, 2, 3");
fontF.setFont(new Font("ttfReal", Font.PLAIN, 20));
frame.add(fontF);
}
}
当我运行代码时,字体似乎是默认字体。我已经将ttf文件加载到Eclipse的项目文件夹中,但是我是否必须给出文件的显式路由? 我试图通过这个基本程序来理解字体,因为我试图将它加载到更大的程序中。
答案 0 :(得分:0)
也许设置一个静态类变量。
public class CustomFonts extends JPanel {
private static Font ttfBase;
}
然后,当您加载字体时,将其加载到ttfBase
。然后在你的主要,
public static void main (String [] args) {
...
Font ttfReal = ttfBase.deriveFont(Font.PLAIN, 20);
fontF.setFont(ttfReal);
...
}