I am making a program where one can click on the window, and a point will be placed there. If the user clicks again, the point will be removed. Programmatically, each click will create a new instance of another class called “Element”, which contains the (X, Y) positions for a single point.
To achieve this, I am extending JPanel and implementing a MouseListener. To draw the points, I’m overriding the paint() method. Every time a user clicks, code the MouseListener’s mouseReleased() either adds to the ArrayList, or removes from it, then calls paint(), where the screen is cleared and the ArrayList is redrawn.
The problem I am having is that the points aren’t going away when clicked on. I don’t know if it’s my lack of understanding of paint(), or something to do with the ArrayList.
Here is my paint():
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);
}
}
And here is the mouse click method:
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();
}
The output of this is as follows:
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)
You should not
add(new Element(roundX, roundY))if the element has been removed in the previous loop