java swing 如何使用自定义字体

使用前需要在resources内配置好字体文件,并在相关的properties配置对应路径。

  1. 使用URL+File。(个人推荐使用这一种)
private 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;
}
  1. 使用getResourceAsStream。(会产生.tmp临时文件)
private 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. 全局字体设置
private 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);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值