Reputation: 103
How to change the color of a JPanel with a mouse click event?
public class Board extends JPanel{
public Board() {
setLayout(new GridLayout(8, 8));
setBackground(Color.white);
setPreferredSize(new Dimension(700, 700));
JPanel[][] squares = new JPanel[8][8];
for(int i = 0; i < squares.length; i++) {
for(int j = 0; j < squares[i].length; j++) {
squares[i][j] = new JPanel();
add(squares[i][j]);
squares[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent click) {
}
});
if(click.getsource() == squares[i][j]) {
squares[i][j].setBackground(Color.blue);
}
if((i+j)%2 == 0)
squares[i][j].setBackground(Color.white);
else
squares[i][j].setBackground(Color.black);
}
}
}
}
Upvotes: 0
Views: 1431
Reputation: 190
You should move the if statement inside the mouseClicked method, something like this:
final int iCopy = i;
final int jCopy = j;
@Override
public void mouseClicked(MouseEvent click) {
if ((iCopy+jCopy)%2==0) {
squares[iCopy][jCopy].setBackground(Color.white);
} else {
squares[iCopy][jCopy].setBackground(Color.black);
}
}
Furthermore I would suggest always use {} in if statements. Otherwise your code could suffer from unexpected errors, since:
if (true)
a += 1;
b += 2;
is the same as
if (true) {
a += 1;
}
b += 2;
which is definitely not what you expected!
Upvotes: 1