2

Something very weird is happening when I use the method :

public void mouseClicked(MouseEvent evt)

I count the number of clicks , and each time that I have one click or two clicks , I grab the (x,y) coordinate and add that coordinate to my list . But when I check the given picture , I see that the added coordinates are also dragged coordinates , i.e. , locations where the user has passed with the mouse , but didn't hit a click or double click .

How can that be ?

This questions is associated with my previous questions regarding polygons , and this problem seems to be the cause of my problems .

Here are the pictures : Closing a polygon

: enter image description here

and when I start to draw something else :

enter image description here

Meaning is , that's the same polygon , only this time the coordinates where the mouse traveled but DIDN'T hit a click / double click , were also counted .

And that's my previous question .

Any idea would to the source of the problem would be greatly appreciated .

The code :

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JPanel;


/**
 * 
 * @author X2
 *
 */
public class Poly
{
    public static void main (String[] args)
    {
     JFrame frame = new JFrame("Draw polygons");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setContentPane(new DrawingPanel());
     frame.pack();
     frame.setVisible(true);
 }
}

Thanks

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318

1 Answers1

4

I am not completely sure of what the exact problem is, but you should not modify your "model" (Polygon/Edge instances) during paintComponent.

When polygonDone is true (btw, you can simply write if(polygonDone)), you are adding new Edges to your model. This sounds bad, as you don't control when paintComponent is called, nor how many times it is called. And since in mouseMoved you call repaint(), this will eventually trigger the call to paintComponent, create new Edges, etc... The problem must lie somewhere in that code. Stop creating Edges in paintComponent.

As a general rule, you should never modify your component state during paintComponent, only upon user input (MouseEvent, KeyBoard events (through KeyBindings)).

Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • I did as you suggested and removed `this.edges.add(currentEdge);` in `public void paintComponent(Graphics g)` , but I got the same thing . – JAN Mar 28 '13 at 05:49
  • Finally I got it fixed ,using your remarks . Thanks a lot . That `paintComponent` was the main reason for this mess . – JAN Mar 28 '13 at 13:43