在鼠标单击上切换图形点

时间:2012-02-12 10:51:30

标签: java swing graphics paintcomponent

我正在制作一个可以点击窗口的程序,并且会在那里放置一个点。如果用户再次点击,则该点将被删除。以编程方式,每次单击将创建另一个名为“Element”的类的新实例,其中包含单个点的(X,Y)位置。

为实现这一目标,我正在扩展JPanel并实现MouseListener。为了绘制点,我重写了paint()方法。每次用户点击时,代码MouseListener的mouseReleased()要么添加到ArrayList,要么从中删除,然后调用paint(),清除屏幕并重新绘制ArrayList。

我遇到的问题是点击后点数不会消失。我不知道是不是我对paint()缺乏了解,或者与ArrayList有关。

这是我的画():

public void paint(Graphics g)
{
    // Clear screen
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, getWidth(), getHeight());

    // Display what elements will be drawn (for debugging)
    System.out.println("About to draw the following elements:");
    for (Element e : elements)
    {
        System.out.println("\t" + e);
    }

    // Draw Elements
    g.setColor(Color.BLACK);
    for(int i=0; i < elements.size(); i++)
    {
        g.fillOval(elements.get(i).x, elements.get(i).y, 10, 10);
    }

}

这是鼠标点击方法:

public void mouseReleased(MouseEvent e)
{
    // Rounds to the nearest grid space (spacing is currently 20px)
    int roundX = (int) ((float)(Math.round(e.getX() / GRID_SPACING)) * GRID_SPACING);
    int roundY = (int) ((float)(Math.round(e.getY() / GRID_SPACING)) * GRID_SPACING);

    System.out.println("Clicked (" + roundX + ", " + roundY + ")");

    // Go through each element...
    for (int i=0; i < elements.size(); i++)
    {
        // if an element exists at the coordinates clicked,
        if (elements.get(i).getX() == roundX && elements.get(i).getY() == roundY)
        {
            // remove it from the elements list
            elements.remove(i);
            i--;
            System.out.println("\tElement exists at (" + roundX + ", " + roundY + "). Removing it.");
        }
    }

    elements.add(new Element(roundX, roundY));

    repaint();
}

输出如下:

  About to draw the following elements: (None)

Clicked (140, 100)
About to draw the following elements:
    This element's coordinates are (140, 100)

Clicked (160, 100)
About to draw the following elements:
    This element's coordinates are (140, 100)
    This element's coordinates are (160, 100)

Clicked (140, 100)
    Element exists at (140, 100). Removing it.
About to draw the following elements:
    This element's coordinates are (160, 100)
    This element's coordinates are (140, 100)

2 个答案:

答案 0 :(得分:4)

如果在前一个循环中删除了该元素,则不应该add(new Element(roundX, roundY))

答案 1 :(得分:2)

不要在Swing面板中覆盖paint(Graphics)。请改用paintComponent(Graphics)