2011-11-29 90 views
1

我在制作4人棋牌游戏时遇到了问题。我无法看到两个ImageIcons是否相同。我为红色,蓝色,绿色和黄色作品提供了四个阵列,我的想法是查看玩家点击的颜色是否与他们的颜色阵列中的任何作品匹配。然而,如果我说如果(colorIcon.equals(clickedIcon))它返回false。我知道那是因为.equals()引用了引用,并且我正在内存中创建新的空间。那么有什么办法可以比较两个ImageIcons?感谢您的回复!比较两个图像图标?

+5

你不应该比较ImageIcons。你有代表棋子的班级吗?如果是这样,你应该比较一下棋子的类型。如果您发现自己需要比较图像图标来解决问题,我认为您的代码中存在设计问题。 – gigadot

回答

1

你总是可以做到:

public class MyImageIcon extends ImageIcon{ 
    String imageColor; 
    // Getters and setters... 
    // Appropriate constructor here. 
    MyImageIcon(Image image, String description, String color){ 
     super(image, description); 
     imageColor = color; 
    } 
    @Override 
    public bool equals(Object other){ 
     MyImageIcon otherImage = (MyImageIcon) other; 
     if (other == null) return false; 
     return imageColor == other.imageColor; 
    } 
} 

而且使用这个类来代替原始的ImageIcon

而是具有:

ImageIcon myImage = new ImageIcon(imgURL, description); 

你会:

MyImageIcon myImage = new MyImageIcon (imgURL, description, "RED"); 
+0

感谢您的帮助,我没有完全做到这样的事情,但我创建了自己的JLabel类并与之合作。 – D347th

+0

很高兴帮助:) – GETah

+0

不应该使用'String.equals()'而不是'String == String'吗? – Bowi

0

.equals()不涉及相同的存储器引用。这是一种比较对象的方法;它是==比较参考。

+2

ImageIcon类继承,但没有实现Object的'equals'方法。根据java doc,Object.equals是:“类Object的equals方法实现对象上最可能的等价关系;也就是说,对于任何非空引用值x和y,此方法返回true当且仅当x和y指** ** same **对象**(x == y的值为true)。**“因此,'equals'和'=='对于'ImageIcon'类 – GETah

+0

完全相同。你就是我的意思.equals – D347th

0

它很简单,因为这:

ImageIcon i=new ImageIcon("getClass().getResource("image.jpg");//this is the image you want to compare to jLabel's icon 
if(jLabel1.getIcon().equals(i){ 
    //...do something 
}