我在制作 4 人国际象棋游戏时遇到了问题。我无法查看两个 ImageIcon 是否相同。我有四个数组用于红色、蓝色、绿色和黄色的棋子,我的想法是查看玩家点击的棋子是否与他们颜色数组中的任何棋子相匹配。但是,如果我说 if(colorIcon.equals(clickedIcon)) 它返回 false。我知道这是因为 .equals() 指的是引用,我在内存中创造了新的空间。那么有什么方法可以比较两个 ImageIcon 吗?感谢阅读!
问问题
6786 次
4 回答
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");
于 2011-11-29T11:05:09.557 回答
0
.equals()
不引用相同的内存引用。这是一种比较对象的方法;就是==
比较参考文献。
于 2011-11-29T11:12:25.133 回答
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
}
于 2017-01-29T06:35:05.903 回答
0
我这样做了:
String Icon1=Button1.getIcon().toString();
String Icon2=Button2.getIcon().toString();
if(Icon1.equals(Icon2)){
System.out.println("Yes");
}else{
System.out.println("No");
}
于 2021-10-03T15:46:10.337 回答