【问题标题】:Font Awesome with SwingSwing 字体真棒
【发布时间】:2014-08-02 08:41:23
【问题描述】:

是否可以将 Font Awesome 与 Swing 应用程序一起使用? 如果可能的话,如何将其图标与摆动组件(JButton 或 JLabel)一起使用。 我之前在我的 Primefaces 应用程序中使用过 Font Awesome。

【问题讨论】:

标签: java swing fonts font-awesome


【解决方案1】:

我会说“是”...

  • Font Awesome下载压缩包
  • 解压
  • fontawesome-webfont.ttf 文件复制到您的项目中(在下面的示例中,我将其用作嵌入式资源)
  • 使用Cheeatsheet,将要使用的图标复制并粘贴到代码中
  • 加载字体并显示...

例如...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestFontAwsome {

    public static void main(String[] args) {
        new TestFontAwsome();
    }

    public TestFontAwsome() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                try (InputStream is = TestFontAwsome.class.getResourceAsStream("/fontawesome-webfont.ttf")) {
                    Font font = Font.createFont(Font.TRUETYPE_FONT, is);
                    font = font.deriveFont(Font.PLAIN, 24f);

                    JLabel label = new JLabel("?");
                    label.setFont(font);

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLayout(new GridBagLayout());
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException | FontFormatException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

}

你也可以直接使用unicode,比如上例中的符号为,可以用作...

 JLabel label = new JLabel("\uf0c0");

【讨论】:

  • @AndrewThompson 是的,我按照网页上的说明复制显示的字符,直接使用 unicode 添加
【解决方案2】:

http://jiconfont.github.io/ 尝试 jIconFont(Swing 或 JavaFX)

例子:

Icon icon = IconFontSwing.buildIcon(FontAwesome.SMILE_O, 40, new Color(0, 150, 0));

JLabel label = new JLabel(icon);

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2017-12-31
    • 1970-01-01
    • 2015-01-23
    • 2017-06-26
    • 2017-12-20
    • 2014-03-02
    • 2014-12-09
    • 1970-01-01
    相关资源
    最近更新 更多