使用自定义字体

  1. 使用URL+File。(个人推荐使用这一种)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    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;
    }
  2. 使用getResourceAsStream。(会产生.tmp临时文件)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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;
    }
  3. 全局字体设置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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);
    }
    }
    }