题
当我制作4个球员国际象棋游戏时,我遇到了问题。我看不到两个Imageicon是否相同。我有四个用于红色,蓝色,绿色和黄色碎片的阵列,我的想法是看看玩家单击的作品是否匹配了颜色阵列中的任何作品。但是,如果我说的是(collicon.equals(clickedicon)),它会返回false。我知道那是因为.equals()是指引用,并且我正在记忆中创建新的空间。那么,有什么方法可以比较两个Imageicon?感谢您的重新加载!
解决方案
您可以随时这样做:
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");
其他提示
.equals()
不参考相同的内存参考。这是一种比较对象的方法;它是 ==
比较参考。
它真的很简单:
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
}
不隶属于 StackOverflow