I'm making a Chess Game in java and I have initialized the board with an array of black and white squares with the help of Swing and AWT. In a subclass (i.e. SetSquaresToClickable
), I wanted the program to go through the squares array(which is a JPanel
2d array), and check if the square contains a piece(which is an ImageIcon
in a JLabel
). If the square does contain a piece, that square should have a MouseListener
. But I can't seem to find the correct if
statement to check and implement all of this.
package mainBoard;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SetSquaresToClickable {
InitializeBoard initializeBoard=new InitializeBoard(); //different class accessed in this class to access components(i.e squares)
JPanel[][] squares=initializeBoard.getSquares();
SetSquaresToClickable() {
for(int i=0;i<8;i++) {
for(int j=0;j<8;j++) {
if(squares[i][j].contains(new JLabel)) { //checks if square contains a piece(does not work)
squares[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
squares[i][j].setBackground(Color.BLUE); //sets square color to blue on being clicked if square contains piece.
}
});
}
}
}
}
public static void main(String[] args) {
new SetSquaresToClickable();
}
}
If someone could help me, that would be great. Thanks in advance.