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

如何将FontAwesome 6 TrueType字体图标转为Java可用Icon?

如何将FontAwesome字体图标转为Swing的Icon对象?

你的场景是在继承AbstractAction的类中需要设置SMALL_ICON和LARGE_ICON_KEY,但这两个属性要求是Icon子类(比如ImageIcon),而FontAwesome是基于字体的图标,无法直接使用。解决思路是自定义一个实现Icon接口的类,用FontAwesome字体绘制图标,具体实现如下:

1. 自定义FontAwesomeIcon类

这个类负责用FontAwesome字体绘制图标,实现Icon接口的三个核心方法:

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;

public class FontAwesomeIcon implements Icon {
    private static Font fontAwesome;
    private char iconChar;
    private int size;
    private Color color;

    // 静态加载FontAwesome字体
    static {
        try (InputStream is = FontAwesomeIcon.class.getResourceAsStream("/path/to/fontawesome-webfont.ttf")) {
            fontAwesome = Font.createFont(Font.TRUETYPE_FONT, is);
            GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fontAwesome);
        } catch (IOException | FontFormatException e) {
            e.printStackTrace();
        }
    }

    public FontAwesomeIcon(char iconChar, int size, Color color) {
        this.iconChar = iconChar;
        this.size = size;
        this.color = color;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2d = (Graphics2D) g.create();
        // 开启抗锯齿让图标更清晰
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 设置字体和颜色
        g2d.setFont(fontAwesome.deriveFont(Font.PLAIN, size));
        g2d.setColor(color);
        // 垂直对齐绘制图标
        FontMetrics metrics = g2d.getFontMetrics();
        int baseline = y + metrics.getAscent();
        g2d.drawString(String.valueOf(iconChar), x, baseline);
        g2d.dispose();
    }

    @Override
    public int getIconWidth() {
        return size;
    }

    @Override
    public int getIconHeight() {
        return size;
    }
}

2. 在Action中使用自定义图标

修改你的EmptyDatabaseAction构造方法,用FontAwesomeIcon替换原来的ImageIcon:

public class EmptyDatabaseAction extends AbstractAction {

    public EmptyDatabaseAction() {
        super(TextLabel.MENU_EMPTY_DB.getMsg());
        // 小图标:示例用垃圾桶图标(对应FontAwesome的'\uf1f8'),大小16,适配系统默认文字颜色
        this.putValue(Action.SMALL_ICON, new FontAwesomeIcon('\uf1f8', 16, UIManager.getColor("Label.foreground")));
        // 大图标:大小24,同色
        this.putValue(Action.LARGE_ICON_KEY, new FontAwesomeIcon('\uf1f8', 24, UIManager.getColor("Label.foreground")));
        this.putValue(Action.SHORT_DESCRIPTION, TextLabel.MENU_EMPTY_DB.getMsg());
    }
    // ... 其他代码
}

注意事项

  • 替换/path/to/fontawesome-webfont.ttf为你项目中FontAwesome字体文件的实际路径
  • 每个FontAwesome图标对应一个Unicode字符,可从FontAwesome官方文档中查询对应字符码
  • 可根据需求调整图标大小、颜色,比如用UIManager的颜色属性适配系统外观

内容的提问来源于stack exchange,提问作者Paul Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:52:43