1

4人用のチェスゲームを作成しているときに問題が発生しました。2つのImageIconが同じかどうかを確認できません。赤、青、緑、黄色のピースに4つの配列があり、プレーヤーがクリックしたピースがカラー配列のいずれかのピースと一致するかどうかを確認するというアイデアでした。ただし、if(colorIcon.equals(clickedIcon))のように言うと、falseが返されます。.equals()が参照を参照し、メモリ内に新しいスペースを作成しているためです。では、2つのImageIconを比較する方法はありますか?リードしてくれてありがとう!

4

4 に答える 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 に答える