双击时,圆圈需要消失

时间:2019-03-17 01:19:15

标签: java swing jframe mouseevent mouselistener

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

我尝试在已实现的方法中用鼠标将圆重新粉刷成与背景相同的颜色,但这并不是很有效。当您按下它时它只会“消失”,但是我希望它在单击时消失。

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

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;

/**
 * In this program, when user clicks a square, a circle appears until the user clicks it again.
 */
public class DD_GridFiller extends JFrame {

    private int gridRows;
    private int gridColumns;

    private Color[][] circleColor;  //color of circles
    private Color lineColor;       //color of lines

    /**
     * constructor
     */
    public DD_GridFiller() {
        setTitle("My Grid Filler");
        setSize(600,600);
        setLayout(new GridLayout(4,4));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        circleColor = new Color[4][4]; //stores the colors in arrays
        gridRows = 4;
        gridColumns = 4;
        lineColor = Color.RED;
        setPreferredSize( new Dimension(90*4, 90*4) );
        setBackground(Color.BLACK); // set the background color for this panel.
        addMouseListener(new MouseListener());

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int top, left;  // position for top left corner of the window
        left = ( screenSize.width - getWidth() ) / 2;
        top = ( screenSize.height - getHeight() ) / 2;
        setLocation(left,top);
        setResizable(false);

        setVisible(true);
        pack();
    }

    public void paint(Graphics g) {
        g.setColor(getBackground());
        g.fillRect(0,0,getWidth(),getHeight());
        int row, col;
        double cellWidth = (double)getWidth() / gridColumns;  //get cell width
        double cellHeight = (double)getHeight() / gridRows;   //get cell height

        //create circles in every cell
        for (row = 0; row < gridRows; row++) {
            for (col = 0; col < gridColumns; col++) {
                if (circleColor[row][col] != null) {
                    int x1 = (int)(col*cellWidth);
                    int y1 = (int)(row*cellHeight);
                    g.setColor(circleColor[row][col]);
                    g.fillOval(x1-2, y1-2, 23*4, 23*4);
                }
            }
        }
        //CREATES THE LINES
        if (lineColor != null) {
            g.setColor(lineColor);
            for (row = 1; row < gridRows; row++) {
                int y = (int)(row*cellHeight);
                g.drawLine(0,y,getWidth(),y);
            }
            for (col = 1; col < gridRows; col++) {
                int x = (int)(col*cellWidth);
                g.drawLine(x,0,x,getHeight());
            }
        }
    }
    /**
     * Finds the row
     * @param pixelY location on x-axis
     * @return rows
     */
    private int findRow(int pixelY) {
        return (int)(((double)pixelY)/getHeight()*gridRows);
    }

    /**
     * Finds the column
     * @param pixelX location of y-axis
     * @return columns
     */
    private int findColumn(int pixelX) {
        return (int)(((double)pixelX)/getWidth()* gridColumns);
    }

    private class MouseListener implements java.awt.event.MouseListener {
         @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

        circleColor[row][col] = new Color(0,223,197);
        repaint(); // redraw the panel by calling the paintComponent method.
    }

    @Override
    public void mousePressed(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
        circleColor[row][col] = new Color(0);
        repaint(); // redraw the panel by calling the paintComponent method.
    }
        @Override public void mouseReleased(MouseEvent e) { }
        @Override public void mouseEntered(MouseEvent e) { }
        @Override public void mouseExited(MouseEvent e) { }
    }
    public static void main (String[] args) {
        new DD_GridFiller();
    }
}

2 个答案:

答案 0 :(得分:1)

您的问题是mousePressed一直将您的颜色设置为黑色。即使您检测到在按下圆圈时颜色不是黑色,在mousePressed中也将其设置为黑色,然后再次绘制圆圈,如此循环。

解决方案实际上很简单:

  1. 删除mousePressed中的所有内容。我们不需要它,mouseClicked实际上已经是mousePressed + mouseReleased。
  2. 将此添加到mouseClicked方法:

    @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.
}

答案 1 :(得分:0)

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

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

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