双击时,圆圈需要消失

我的代码中的问题是,我试图制作一个程序,当你点击网格中的单元格时,该单元格内应该会出现一个圆圈。我对此很满意。但是,当您第二次单击时,圆圈应该会消失。我不知道该怎么做。

我尝试将圆圈重新绘制为与实现方法中的背景相同的颜色,鼠标按下,但这并不是很有效。它只有在你按下它时才会“消失”,但我希望它在点击时消失。

我把它写成鼠标按下,因为我不知道如何在鼠标点击方法中使用它。

https://i.stack.imgur.com/M67ei.gif


慕森卡
浏览 101回答 2
2回答

慕村225694

你的问题是一直把你的颜色设置为黑色。即使您检测到按下圆圈时颜色不是黑色的,在mousePressed中,您再次将其设置为黑色,然后再次绘制圆圈,就像这样在循环中。mousePressed解决方案实际上非常简单:删除 中的所有内容。我们不需要它,mouseClicked基本上已经只是mousePressed + mouseRelease。mousePressed将其添加到鼠标单击的方法:@Overridepublic 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.}

忽然笑

您的方法测试颜色的行/列位置;如果它是非空的,它会画一个圆,对吧?也许在mousePressed中,您可以测试该位置的circleColor是否为非空,如果是,则将其设为空。paint我不清楚重绘是否正在填充单元格;它可能需要这样做才能在绘制圆圈后覆盖圆圈。在这样的应用程序中,通常计算需要重新绘制的最小矩形,然后仅重新绘制它 - 您可以通过计算该矩形并将其坐标传递到重绘方法中来执行此操作,然后仅绘制与更改的矩形相交的组件部分。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java