开发者

Drawing ZigZags in Java

开发者 https://www.devze.com 2023-04-11 17:45 出处:网络
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:

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 Collection of 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 your mouseClicked, 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.


Smells like homework.

You're not clearing the array when the user stops drawing. When they click the first point of the new figure the last point of the old figure is still at the end of the array, so your paint function faithfully draws a line between them. If you clear the array when they stop drawing it should behave how you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号