How to find array coordinates with Mouse Listener

603 views Asked by At

Instead of hard coding 64 buttons to create a board did a 2D array and I need to get the array coordinates. This is the code I tried using and the error I got.

code:

public void mousePressed(MouseEvent e)
    {
        JButton[][] clicked = (JButton[][])e.getSource();
        int x = clicked.length;
        int y = clicked[0].length;
        board[x][y].setIcon(selected);
    }

Error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to [[Ljavax.swing.JButton;
1

There are 1 answers

0
bokhyfg On

I figured out how to not hard code each option use a for loop for the action listener and use variables.

Solution:

public void mousePressed(MouseEvent e)
{
    JButton clicked = (JButton)e.getSource();
    for(int x = 0; x<8; x++)
    {
        for(int y = 0;y<8;y++)
        {
            if(clicked == board[x][y])
            {
                occupied[x][y] = true;
                board[x][y].setIcon(selected);
            }
        }
    }
}