Question

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!

Was it helpful?

Solution

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");

OTHER TIPS

.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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top