JButton 文本的抗锯齿

Hun*_*gry 5 java fonts swing jbutton font-awesome

我在 JButton 中使用Font Awesome创建一个可单击的图标,但是当尺寸较小时,生成的图标会出现别名。作为一点背景知识,Font Awesome是一个可下载的ttf文件(字体文件),其中每个字符都是一个“可缩放矢量图标”。paintComponent查看了 Google 和堆栈溢出之前的答案后,我尝试通过覆盖JButton 的方法来强制抗锯齿;然而这似乎没有效果:

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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

下图显示了字体大小为 30、100 和 200 时生成的字体图标:

在此输入图像描述 在此输入图像描述 在此输入图像描述

如何强制对小字体进行抗锯齿?

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

sta*_*cer 2

JLabel 会进行适当的文本提示,因此您可以将 Font Awesome 文本放入 JLabel 中,然后将 JLabel 放入 JButton 中:

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

    JButton iconButton = new JButton( );
    iconButton.add( iconLabel );
Run Code Online (Sandbox Code Playgroud)

这成功解决了Linux 上使用 NimROD L&F 的问题。期望它也能在其他配置上工作似乎是合理的,但是 YMMV。