0

Im making a "memorycard game" and im trying to check if the two Icons match, how can I compare Icons? (they are set on jLabels). I'm currently just using if(lbl1.getIcon() == lbl8.getIcon())

lbl1.addMouseListener(new MouseListener() {

        public void mouseReleased(MouseEvent e) {

        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseClicked(MouseEvent e) {

           lbl1.setIcon(new 
ImageIcon(getClass().getResource("/pictures/teo.png")));
           i++;
           if(i == 2)
           {
               i = 0;
              if(lbl1.getIcon() == lbl8.getIcon())
              {
                  System.out.println("match");
              }

           }
        }
    });
  • You do not mention what the problem is. If your current code (`if(lbl1.getIcon() == lbl8.getIcon()`) is working, which is doubtful but unstated, what is your question? – Zephyr Feb 08 '19 at 22:30
  • 1
    [Never ever, EVER compare objects with `==` unless you know exactly what you are doing and why you are doing it.](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Turing85 Feb 08 '19 at 22:31
  • @Zephyr it is not working, thats why im asking –  Feb 08 '19 at 22:31
  • 1
    @LeonardBD "*it is not working*" - [Questions seeking debugging help (*"why isn't this code working?"*) must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.](https://stackoverflow.com/help/on-topic) See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Turing85 Feb 08 '19 at 22:32
  • In general, you need an object model that can be properly compared. For example, instead of creating two different labels (`lbl1` and `lbl2`), simply display `lbl1` twice. Then you can easily compare if the selected labels match with `if (selectedLabel[0].equals(selectedLabel[1])`. You do not show enough of your code to really give a definitive answer, though. I recommend you [edit] your question and provide a [mcve] that demonstrates. – Zephyr Feb 08 '19 at 22:33
  • 1
    Why do you want to compare icons? This sounds like an XY problem where you have already chosen a solution for an underlying problem but where there are other, better solutions available. Unless you're doing image manipulation you shouldn't need to compare the visuals of icons – Erwin Bolwidt Feb 08 '19 at 23:23

0 Answers0