将自定义字体加载到Java中
大家好,我在将自定义字体加载到Java时遇到了一些问题将自定义字体加载到Java中,java,swing,fonts,awt,embedded-resource,Java,Swing,Fonts,Awt,Embedded Resource,大家好,我在将自定义字体加载到Java时遇到了一些问题 public class CustomFonts extends JPanel { public static void loadFont() throws FontFormatException, IOException { String fontFileName = "stocky.ttf"; InputStream is = CustomFonts.class.getClassLoader()
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的项目文件夹中,但是我是否必须给出文件的显式路径?
我试图通过这个基本程序来理解字体,因为我试图将它加载到一个更大的程序中。也许可以设置一个静态类变量
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);
...
}
您的自定义字体设置不正确,因为找不到名为
ttfReal
的字体registerFont
不按字体对象的局部变量名命名字体。您可以通过确定自定义字体的名称,但您可能会发现,只要将自定义字体存储在类变量中并在需要设置其版本时从中派生,就更容易了。