Comparing ImageIcons in 2 JButtons

时间:2016-03-02 10:52:09

标签: java

I wonder why am getting null in my comparison that checks if two JButtons have the same ImageIcon? Here is my class

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

My question is basically why i get null when i do (ImageIcon)this.getIcon().getDescription(). It seems like setIcon only sets only ImageIcon and not the Icon. Because it shows on the JButton that an ImageIcon is present but when i try to retrieve it, it get null

1 个答案:

答案 0 :(得分:0)

我更改为Resize方法以返回Image,因此它看起来如下

    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变量,因此更容易获取位置字符串。我比较字符串。

我知道比较字符串有点不明智,但事实证明它是一种出路