【问题标题】:Text not show correct FontAwesome and Swing文本未显示正确的 FontAwesome 和 Swing
【发布时间】:2016-11-11 19:12:37
【问题描述】:

我试着按照这个例子Font Awesome with Swing

一切正常,但是当我尝试添加一些文本时字体显示不正确,它向我显示如下内容:

我的代码

....
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("\uf0c0 font not correct");
    label.setFont(font);
    label.setForeground(Color.red);

    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();
}
....

结果

我已经安装了字体:

对这个问题有任何想法吗?

【问题讨论】:

    标签: java swing fonts font-awesome


    【解决方案1】:
    JLabel label = new JLabel("\uf0c0 font not correct");
    

    JLabel 字体设置为 Font Awesome,它没有 JLabel 中提供的 ascii 文本的字形。 AFAIK 没有办法在单个 JLabel 中混合字体 - 您可以使用某种形式的 html 来做到这一点,但更简单的解决方案可能是只使用两个具有不同字体的 JLabel。

    JLabel l1 = new JLabel("\uf0c0");
    JLabel l2 = new JLabel("This is ascii text");
    l1.setFont(fontAwesome);
    Box mix = Box.createHorizontalBox();
    mix.add(l1); mix.add(l2);
    myContainer.add(mix);
    

    您也可以使用paintComponent 自定义绘制组件,根据需要设置字体。

    【讨论】:

    • 谢谢@copeg,这是关于 JLabel 而 JButton 呢?我不能做两个标签吗?
    • and what about the JButton 您可以尝试通过覆盖paintComponent 并根据需要设置字体来尝试自定义绘画。
    • 拖曳其他按钮策略。 1) 按钮也支持 HTML(但当按钮被禁用时看起来不正确,因为文本不会改变颜色) 2) 将 FontAwesome 字形动态转换为图像,并将图像用作图标按钮。这是turning glyphs into images 的一个(稍微复杂的)示例。
    • 谢谢@AndrewThompson 的回答 :)
    • 从技术上讲,这不是一个答案,只是一个评论。但不客气。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多