I have a design project and I’m supposed to draw zigzags in Java, using my mouse. First of all, I’m using MouseListener and in mouseClicked method, I gather all the points that the user clicks:
public void mouseClicked(MouseEvent e){
if(isAbleToDraw){
corners[points]=e.getPoint();
points++;
repaint();
}
}
Here I use a boolean “isAbleToDraw” to check whether the user clicked “draw” or “stop drawing” buttons.
And then, I draw the zigzags like this:
super.paintComponent(graph);
Graphics2D g = (Graphics2D) graph;
g.drawLine(corners[i].x, corners[i].y, corners[i+1].x, corners[i+1].y);
Finally, the problem is, when I clicked on “stop drawing” button after drawing a zigzag, and then after clicking the “draw” button again, it keeps drawing the lines from the last point it left. In other words, I can’t draw 2 different seperate zigzags.
Any idea about how to solve the issue?
If you want the user to be able to draw more than one zig-zag and see them both on the screen, then you could use a
Collectionof point arrays. Each time the user clicks the “draw” button, you add a new array to the collection and make that new array the active array. In yourmouseClicked, you can add the points that the user clicks to active point array and when you paint the component, rather than just drawing the one zig-zag, iterate through the collection of arrays and draw them all.