【问题标题】:Compare two image icons?比较两个图像图标?
【发布时间】:2011-11-29 10:57:05
【问题描述】:

我在制作 4 人国际象棋游戏时遇到了问题。我无法查看两个 ImageIcon 是否相同。我有四个数组用于红色、蓝色、绿色和黄色的棋子,我的想法是查看玩家点击的棋子是否与他们颜色数组中的任何棋子相匹配。但是,如果我说 if(colorIcon.equals(clickedIcon)) 它返回 false。我知道这是因为 .equals() 指的是引用,我在内存中创造了新的空间。那么有什么方法可以比较两个 ImageIcon 吗?感谢阅读!

【问题讨论】:

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

标签: java swing compare imageicon


【解决方案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");

【讨论】:

  • 感谢您的帮助,我并没有完全做这样的事情,但我创建了自己的 JLabel 类并使用它。
  • 不应该使用String.equals()而不是String == String吗?
【解决方案2】:

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

【讨论】:

  • ImageIcon 类继承但不实现 Objectequals 方法。 Object.equals 根据 java doc 是:“类 Object 的 equals 方法实现了对象上最有区别的可能等价关系;也就是说,对于任何非空引用值 x 和 y,当且仅当 x 和y 指的是 same 对象 (x == y 的值为 true)。" 因此,equals==ImageIcon 完全相同类
  • 谢谢你就是我所说的 .equals 的意思
【解决方案3】:

其实很简单:

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
}

【讨论】:

    【解决方案4】:

    我这样做了:

    String Icon1=Button1.getIcon().toString();
    String Icon2=Button2.getIcon().toString();
    
    if(Icon1.equals(Icon2)){
       System.out.println("Yes");
    }else{
       System.out.println("No");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2013-12-30
      • 2018-04-26
      相关资源
      最近更新 更多