为了账号安全,请及时绑定邮箱和手机立即绑定

双击时,圆圈需要消失

双击时,圆圈需要消失

慕森卡 2022-08-17 12:31:31
我的代码中的问题是,我试图制作一个程序,当你点击网格中的单元格时,该单元格内应该会出现一个圆圈。我对此很满意。但是,当您第二次单击时,圆圈应该会消失。我不知道该怎么做。我尝试将圆圈重新绘制为与实现方法中的背景相同的颜色,鼠标按下,但这并不是很有效。它只有在你按下它时才会“消失”,但我希望它在点击时消失。我把它写成鼠标按下,因为我不知道如何在鼠标点击方法中使用它。https://i.stack.imgur.com/M67ei.gif
查看完整描述

2 回答

?
慕村225694

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.

}


查看完整回答
反对 回复 2022-08-17
?
忽然笑

TA贡献1806条经验 获得超5个赞

您的方法测试颜色的行/列位置;如果它是非空的,它会画一个圆,对吧?也许在mousePressed中,您可以测试该位置的circleColor是否为非空,如果是,则将其设为空。paint

我不清楚重绘是否正在填充单元格;它可能需要这样做才能在绘制圆圈后覆盖圆圈。

在这样的应用程序中,通常计算需要重新绘制的最小矩形,然后仅重新绘制它 - 您可以通过计算该矩形并将其坐标传递到重绘方法中来执行此操作,然后仅绘制与更改的矩形相交的组件部分。


查看完整回答
反对 回复 2022-08-17
  • 2 回答
  • 0 关注
  • 100 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号