2つの画像アイコンを比較しますか?
質問
私は4奏者のチェスゲームを作っている間に問題に遭遇しました。 2つのImageConsが同じかどうかはわかりません。赤、青、緑、黄色のピース用の4つの配列があり、私のアイデアは、プレイヤーがクリックしたピースがカラーアレイのいずれかのピースを一致させたかどうかを確認することでした。ただし、if(coloricon.equals(clickedicon))のように言ったら、falseを返します。それは、.equals()が参照を指すためであり、私はメモリに新しいスペースを作っているためです。それで、私が2つのイメージイコンを比較する方法はありますか?リアードしてくれてありがとう!
解決
あなたはいつでもできる:
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