使用鼠标单击更改JPanel的颜色

时间:2015-11-05 07:18:26

标签: java colors jpanel mouselistener

如何使用鼠标单击事件更改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); 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您应该在mouseClicked方法中移动if语句,如下所示:

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;

这绝对不是你所期望的!