比较 2 个 JButton 中的图像图标



我想知道为什么在我的比较中得到空,检查两个JButton是否具有相同的图像图标?这是我的班级

public class Card extends JButton{

    // Instance Variables
    private ImageIcon icon;
    private static final int CARD_SIZE = 165;
    public Card(ImageIcon icon){
        setIcon(ResizeIcon(icon));
        this.icon = icon;
        setOpaque(true);
        setBorder(new EmptyBorder(0,0,0,0));
        // Preferred card size
        setPreferredSize(new Dimension(CARD_SIZE, CARD_SIZE));
    }
    public boolean SameIcon(Card card){
        System.out.println(((ImageIcon)this.getIcon()).getDescription());
        return getIcon() == card.getIcon();
    }
    // Resize the image to fit into JButton regardless of its original dimensions
    private ImageIcon ResizeIcon(ImageIcon imagIcon){
        Image img = imagIcon.getImage(); 
        Image newimg = img.getScaledInstance(CARD_SIZE - 5, CARD_SIZE - 5,  java.awt.Image.SCALE_SMOOTH);  
        return new ImageIcon(newimg);
    }
}

我的问题基本上是为什么当我这样做时我得到空(ImageIcon)this.getIcon().getDescription()。似乎setIcon只设置ImageIcon而不是Icon。因为它在 JButton 上显示存在图像图标,但当我尝试检索它时,它变为空

我更改为调整大小方法以返回图像,因此它如下所示

    private Image ResizeIcon(ImageIcon imagIcon){
        return (imagIcon.getImage()).getScaledInstance(
                       CARD_SIZE - 5, 
                       CARD_SIZE - 5,  
                       java.awt.Image.SCALE_SMOOTH);  
    }

那么当调用任何特定 JButton 的 setIcon() 方法时,我说

setIcon(new ImageIcon(ResizeIcon(icon), icon.toString()));

请记住,icon 是一个 ImageIcon 变量,因此更容易获取位置字符串。我比较字符串。

我知道比较字符串有点不明智,但事实证明这是暂时的出路

最新更新