2015-11-05 50 views
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); 
      } 
     } 
    } 
} 

回答

1

你應該將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; 

這絕對不是你所期望的!

+0

我同意大括號位,但由於'MouseAdapter'是一個匿名的內部類,是不是'i'和'j'必須是最終的? – CarefreeCrayon

+0

是的,我改變了它 –

+0

如果這個答案對您有幫助,請標記爲正確 –