如何使用鼠标单击事件更改JPanel的颜色?
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);
}
}
}
}
最佳答案
您应该将if语句移动到mouseClicked方法中,如下所示:
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);
}
}
此外,我建议在if语句中始终使用{}。否则,代码可能会遭受意外错误,因为:
if (true)
a += 1;
b += 2;
是相同的
if (true) {
a += 1;
}
b += 2;
这绝对不是您所期望的!
关于java - 用鼠标单击更改JPanel的颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33538672/