You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Swing为JLabel加载特殊字体失效问题求助

Fix: Custom Font Not Loading for JLabel in Swing

嘿,我一眼就揪出你代码里的问题了!导致title JLabel没显示出"you murderer bb"字体的原因是一个低级但容易犯的变量名错误——你在派生字号的时候用错了对象!

问题根源看这里:

在加载titleFont的代码块里,你写完titleFont = Font.createFont(...)之后,紧接着写了:

titleFont = font.deriveFont(40f);

这里的font是你之前加载的Nunito字体对象啊!相当于你刚把"you murderer bb"字体加载到titleFont里,立刻就用Nunito字体的40号版本覆盖了它,难怪title显示的是大号常规字体(其实是Nunito的40号,只是你误以为是系统常规字体)。

修正后的代码片段

把那行错误的代码改成用titleFont自己来派生字号:

private Font titleFont;
File fontFile = new File("resources\\fonts\\youmurdererbb_reg.ttf");
try {
    titleFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
    // 这里改成titleFont.deriveFont,而不是font.deriveFont!
    titleFont = titleFont.deriveFont(40f);
} catch (FontFormatException | IOException e) {
    e.printStackTrace();
}

额外的优化建议(避免后续踩坑)

  • 用getResourceAsStream替代File:如果你的项目打包成JAR文件,File路径会失效,改用类加载器获取资源流更可靠:
    InputStream fontStream = getClass().getResourceAsStream("/resources/fonts/youmurdererbb_reg.ttf");
    titleFont = Font.createFont(Font.TRUETYPE_FONT, fontStream);
    
  • 注册字体到系统:加载字体后注册到GraphicsEnvironment,确保Swing能全局识别它,避免一些奇怪的渲染问题:
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    ge.registerFont(titleFont);
    
  • 检查字体文件:确认youmurdererbb_reg.ttf文件没有损坏,文件名和路径完全匹配(注意大小写,Windows不敏感但Linux/Mac敏感)。

这样修改后,你的title JLabel应该就能正常显示"you murderer bb"字体的40号大小了!

内容的提问来源于stack exchange,提问作者Abdelraim Chernai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:18:11