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
我不清楚重绘是否正在填充单元格;它可能需要这样做才能在绘制圆圈后覆盖圆圈。
在这样的应用程序中,通常计算需要重新绘制的最小矩形,然后仅重新绘制它 - 您可以通过计算该矩形并将其坐标传递到重绘方法中来执行此操作,然后仅绘制与更改的矩形相交的组件部分。
添加回答
举报