比较两个图像图标?

时间:2011-11-29 10:57:05

标签: java swing compare imageicon

我在制作4人棋牌游戏时碰到了一个问题。我无法看到两个ImageIcons是否相同。我有四个用于红色,蓝色,绿色和黄色的阵列,我的想法是看看玩家点击的那个棋子是否与他们的颜色阵列中的任何棋子相匹配。但是如果我说if(colorIcon.equals(clickedIcon))它返回false。我知道那是因为.equals()引用了引用,我在内存中创建了新的空间。那么有什么方法可以比较两个ImageIcons吗?谢谢你的报道!

3 个答案:

答案 0 :(得分: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");

答案 1 :(得分:0)

.equals()不引用相同的内存引用。这是一种比较对象的方法;它是==比较参考文献。

答案 2 :(得分: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
}
相关问题