Java MouseClick Listener not working

awteventsjavalistenermouselistener

So I'm working on a deal or no deal java game essentially, and right now I'm trying to have the image icon disappear where the user clicked. So I have an 6 by 6 array of 'metal briefcase' (casesArray) image icons, but regardless of where the user clicks, only the image icon in the top left disappears. I'm guessing this is just a logic mistake on my part, but I can't seem to figure out what I'm doing wrong…

class MouseClickListener implements MouseListener
    {
        public void mouseClicked (MouseEvent event)
        {
            if (event.getX() <= 133)row=0;
            else if (event.getX() <= 267 && event.getX()>133)row=1;
            else if (event.getX() <= 400 && event.getX()>267)row=2;
            else if (event.getX() <= 533 && event.getX()>400)row=3;
            else if (event.getX() <= 667 && event.getX()>533)row=4;
            else if (event.getX() <= 800 && event.getX()>667)row=5;
             if (event.getY() <= 100)column=0;
            else if (event.getY() <= 200 && event.getY() > 100)column=1;
            else if (event.getY() <= 300 && event.getY() > 200)column=2;
            else if (event.getY() <= 400 && event.getY() > 300)column=3;
            else if (event.getY() <= 500 && event.getY() > 400)column=4;
            else if (event.getY() <= 600 && event.getY() > 500)column=5;

            casesArray[row][column].setIcon(null);
            repaint();
        }
    .
    .
    .
    .
for(int i=0; i<6; i++)
    {
        for(int j=0; j<6; j++)
        {
            casesArray[i][j].addMouseListener(new MouseClickListener());
        }
    }

Best Solution

MouseEvents are contextual to the component that raised them. That is, the x/y point of the event is automatically converted to the coordinate space of the component that the event occurred on.

So, if a component exists at 100x100 within it's parent, when you click on it, the mouse event will be converted so coordinates are 0x0, representing the top level corner of the component that was clicked.

Instead of using a series of if statements, try actually referencing the component directly...

class MouseClickListener implements MouseListener
{
    public void mouseClicked (MouseEvent event)
    {
        Component comp = event.getComponent();
        if (comp instanceof JLabel) {
            ((JLabel)comp).setIcon(null);
        }
    }
}

Updated with additional example

MouseEvent#getSource returns a reference to the object that created the event...

class MouseClickListener implements MouseListener
{
    public void mouseClicked (MouseEvent event)
    {
        Object source = event.getSource();
        for (int x = 0; x < casesArray.length; x++) {
            for (int y = 0; y < casesArray[x].length; y++) {
                if (casesArray[x][y] == source) {
                    casesArray[x][y].setIcon(null);
                    break;
                }
            }
        }
    }
}

A safer solution would be to continue using getComponent as the source of the event could potentially be different to the component that the event occurred on...

class MouseClickListener implements MouseListener
{
    public void mouseClicked (MouseEvent event)
    {
        Component source = event.getComponent();
        for (int x = 0; x < casesArray.length; x++) {
            for (int y = 0; y < casesArray[x].length; y++) {
                if (casesArray[x][y] == source) {
                    casesArray[x][y].setIcon(null);
                    break;
                }
            }
        }
    }
}

Working example

enter image description here

This basically loads a bunch of images from a folder and displays them in a 6x6 grid. Click on any image will set it's corresponding label's icon to null

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ClickTest {

    public static void main(String[] args) {
        new ClickTest();
    }

    public ClickTest() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel[][] casesArray;

        public TestPane() {

            setLayout(new GridLayout(0, 6));

            File[] files = new File("/path/to/lots/of/images").listFiles();

            MouseListener listener = new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent event) {
                    Object source = event.getSource();
                    for (int x = 0; x < casesArray.length; x++) {
                        for (int y = 0; y < casesArray[x].length; y++) {
                            if (casesArray[x][y] == source) {
                                casesArray[x][y].setIcon(null);
                                break;
                            }
                        }
                    }
                }
            };

            casesArray = new JLabel[6][6];
            int index = 0;
            for (int x = 0; x < 6; x++) {
                for (int y = 0; y < 6; y++) {
                    JLabel label = new JLabel();
                    try {
                        label.setIcon(new ImageIcon(ImageIO.read(files[index++])));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    label.addMouseListener(listener);
                    casesArray[x][y] = label;
                    add(casesArray[x][y]);
                }
            }
        }
    }
}