0
如何用鼠標點擊事件改變JPanel的顏色?用鼠標點擊改變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);
}
}
}
}
我同意大括號位,但由於'MouseAdapter'是一個匿名的內部類,是不是'i'和'j'必須是最終的? – CarefreeCrayon
是的,我改變了它 –
如果這個答案對您有幫助,請標記爲正確 –