2016-03-02 19 views
0

我想知道爲什麼我的比較中檢查兩個JButton是否具有相同的ImageIcon?這裏是我的類比較兩個JButton中的ImageIcons

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而不是圖標。因爲它顯示了一個JButton是一個ImageIcon存在,但是當我試圖找回它,它得到空

+0

我試圖做一個「的System.out.println(((ImageIcon的)this.getIcon() ).getDescription());」在SameIcon類中,但是我所有的都是空的 –

回答

0

我改調整方法返回一個圖片代替它看起來如下

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

記住,圖標是一個ImageIcon變量,因此它更容易獲得位置字符串。我比較字符串。

我知道它有點不明智的比較字符串,但事實證明這是一條出路:l,暫且