JButton文本的抗锯齿

时间:2014-09-22 14:16:28

标签: java swing fonts jbutton font-awesome

我在JButton中使用Font Awesome来创建可点击的图标,但是当尺寸较小时,生成的图标会显示别名。正如一些背景知识,Font Awesome是一个可下载的ttf文件(字体文件),其中每个字符都是一个可缩放的矢量图标'。看过谷歌以前的答案和堆栈溢出,我试图通过覆盖JButton的paintComponent方法来强制消除锯齿;然而,这似乎没有效果:

import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Test extends JFrame{

    public Test(){
        Font fontAwesome = null;
        try {
            fontAwesome = Font.createFont(Font.TRUETYPE_FONT, new File("font-awesome-4.2.0\\fonts\\fontawesome-webfont.ttf"));
            fontAwesome = fontAwesome.deriveFont(Font.PLAIN, 100);
        } catch (FontFormatException | IOException e) {
            e.printStackTrace();
        }

        JButton iconButton = new JButton("\uf0a8"){
            @Override
            public void paintComponent(Graphics g) {
                Graphics2D graphics2d = (Graphics2D) g;
                graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                //graphics2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                //graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                //graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                super.paintComponent(graphics2d);
            }
        };

        iconButton.setFont(fontAwesome);
        iconButton.setFocusPainted(false);

        this.add(iconButton);
        this.setVisible(true);
        this.pack();
    }

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

以下图像显示了字体大小为30,100和200的结果字体图标:

enter image description here enter image description here enter image description here

如何为小字体强制消除锯齿?

更新:我使用内置的java字体而不是Font Awesome测试了相同的代码,并且完全相同的问题也适用。

1 个答案:

答案 0 :(得分:1)

JLabel进行正确的文本提示,因此您可以将Font Awesome文本放在JLabel中,然后将JLabel放在JButton中:

    JLabel iconLabel = new JLabel( "\uf0a8" );
    iconLabel.setFont( fontAwesome );

    JButton iconButton = new JButton( );
    iconButton.add( iconLabel );

这个解决使用NimROD L& F成功解决了Linux上的问题。似乎有理由期望它也适用于其他配置,但YMMV。

相关问题