문제

I ran into an issue while I'm making a 4 player chess game. I am unable to see if two ImageIcons are the same. I have four arrays for the red, blue, green, and yellow pieces and my idea was to see if what piece the player clicked on matched any of the pieces in their color array. However if I say like if(colorIcon.equals(clickedIcon)) it returns false. I know that is because .equals() refers to the reference and I'm making new space in the memory. So is there any way I can compare two ImageIcons? Thanks for reaading!

도움이 되었습니까?

해결책

You can always do:

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;
   }
}

And use this class instead of a raw ImageIcon

Instead of having:

ImageIcon myImage = new ImageIcon(imgURL, description);

you would have:

MyImageIcon myImage = new MyImageIcon (imgURL, description, "RED");

다른 팁

.equals() doesn't refer to the same memory reference. It's a method that compares the objects; it's == that compares the references.

Its really simple as this:

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top