tags:

views:

151

answers:

1

How can I copy a polygon to a new location. I use e.isPopupTrigger() to select the polygon, but I dont know how to copy it. Is the function of copy similar to the function of translate? e.g. polygon.translate(x,y)?

Thanks.

EDITED:

//this code doesnt work :-(

if(e.getSource() == Copy){  
  Polygon copyPolygon = new Polygon();
  copyPolygon = selectedTriangle;
  copyPolygon.translate(2, 2);
  repaint();
}

The problem has been solved with these code :-)

if(e.getSource() == Copy){    
  Polygon copyPolygon = new Polygon(selectedTriangle.xpoints,selectedTriangle.ypoints,selectedTriangle.npoints);
  copyPolygon.translate(10,10);
  triangles.add(copyPolygon);
  repaint();
}
A: 

You could construct a new polygon from the old one, then move that polygon to a new location

Polygon newPolygon = new Polygon(oldPolygon.xpoints, oldPolygon.ypoints, oldPolygon.npoints);
newPolygon.translate(newXPos, newYPos);

Your code doesn't work because the line

copyPolygon = selectedTriangle;

Doesn't make a copy of selectedTriangle, it just makes copyPolygon point to the same object. So you need to construct a new polygon that is identical to the original, which is what the first line in my suggestion does.

Nali4Freedom
Also '= new Polygon();' is redundant given the next line. There's no need to create a new polygon before cloning the original.
Chris Nava
I have tried to change the code but I keep getting this error : The method clone() in type object is not visible.
Jessy
Ah, my mistake, Polygon isn't actually cloneable. It gives you that error because clone is a protected member of object, and not overridden by some function in Polygon. In that case, go with my first suggestion which should make a new polygon with the same points as the old one.
Nali4Freedom
Im still not success.Polygon copyPolygon = new Polygon(selectedTriangle.xpoints,selectedTriangle.ypoints,selectedTriangle.npoints);copyPolygon.translate(10,10);
Jessy
Is your paint function drawing the copied polygon? This code only creates a copy, you'll still have to draw it in the paint function. You could add the copied polygon to an array that you then iterate through and draw in the paint function, that way it would handle any number of additional polygons.
Nali4Freedom