2 回答

TA貢獻1880條經驗 獲得超4個贊
你的問題是一直把你的顏色設置為黑色。即使您檢測到按下圓圈時顏色不是黑色的,在mousePressed中,您再次將其設置為黑色,然后再次繪制圓圈,就像這樣在循環中。mousePressed
解決方案實際上非常簡單:
刪除 中的所有內容。我們不需要它,mouseClicked基本上已經只是mousePressed + mouseRelease。mousePressed
將其添加到鼠標單擊的方法:
@Override
public void mouseClicked(MouseEvent e) {
int row, col; // the row and column in the grid of squares where the user clicked.
row = findRow( e.getY() ); col = findColumn( e.getX() ); //find the location of cells clicked
System.out.println("Cell color: " + circleColor[row][col]); //will let you see whats happening
if (circleColor[row][col] == null) {
circleColor[row][col] = new Color(0,223,197);
} else {
circleColor[row][col] = null;
}
repaint(); // redraw the panel by calling the paintComponent method.
}
我們正在做什么 - 最初我們所有的顏色都是空的(在你的代碼中,mousePressed將它們設置為RGB [0,0,0],即黑色)。因此,當我們第一次單擊單元格并看到單元格顏色為“null”(即其為空)時,我們將圓圈顏色設置為新顏色并繪制圓圈。如果我們再次按下,我們檢測到顏色不再是“空”,即單元格內部有一個圓圈 - 然后我們將單元格設置回null。
有些人可能不喜歡Colors的“null”概念 - 如果您想要RGB [0,0,0]而不是null,只需將null的任何初始出現轉換為RGB [0,0,0],然后使用它:
public void mouseClicked(MouseEvent e) {
...
//initial setup
if (circleColor[row][col] == null) {
circleColor[row][col] = new Color(0);
}
System.out.println("Cell color: " + circleColor[row][col]); //will let you see whats happening
if (circleColor[row][col].equals(Color.getHSBColor(0,0,0))) {
circleColor[row][col] = new Color(0,223,197);
} else {
circleColor[row][col] = new Color(0) ;
}
repaint(); // redraw the panel by calling the paintComponent method.
}

TA貢獻1806條經驗 獲得超5個贊
您的方法測試顏色的行/列位置;如果它是非空的,它會畫一個圓,對吧?也許在mousePressed中,您可以測試該位置的circleColor是否為非空,如果是,則將其設為空。paint
我不清楚重繪是否正在填充單元格;它可能需要這樣做才能在繪制圓圈后覆蓋圓圈。
在這樣的應用程序中,通常計算需要重新繪制的最小矩形,然后僅重新繪制它 - 您可以通過計算該矩形并將其坐標傳遞到重繪方法中來執行此操作,然后僅繪制與更改的矩形相交的組件部分。
添加回答
舉報