Reputation: 37
I have created a custom Path2D class to draw an H-shaped "calliper" on screen, for a project I am doing. I want to drag and eventually resize the calliper on screen. I have managed to get the Path2D set up so I can draw the calliper, and the code looks like this:
Declaration and Constructor:
public class Calliper extends Path2D.Double
{
// X and Y coordinates of all six points on Calliper
double cX1, cX2, cX3, cX4, cX5, cX6;
double cY1, cY2, cY3, cY4, cY5, cY6;
// Width and Height
double cWidth;
double cHeight;
public Calliper(double x, double y, double w, double h)
{
cWidth = w;
cHeight = h;
cX1 = x;
cY1 = y;
cX2 = x;
cY2 = y + (h/2);
cX3 = x;
cY3 = y + h;
cX4 = x + w;
cY4 = y;
cX5 = cX4;
cY5 = cY4 + (h /2);
cX6 = cX4;
cY6 = cY4 + h;
build();
}
build() method (used to draw the path) and setCalliper() method, used to redefine the coordinates, or width, height:
private void build()
{
// Draw the path for the calliper
moveTo(cX1, cY1);
lineTo(cX2, cY2);
lineTo(cX3, cY3);
moveTo(cX2, cY2);
lineTo(cX5, cY5);
moveTo(cX4, cY4);
lineTo(cX6, cY6);
}
public void setCalliper(double x, double y, double w, double h)
{
// Rebuild the calliper using different x,y coordinates, or
// different width/height
cWidth = w;
cHeight = h;
cX1 = x;
cY1 = y;
cX2 = x;
cY2 = y + (h/2);
cX3 = x;
cY3 = y + h;
cX4 = x + w;
cY4 = y;
cX5 = cX4;
cY5 = cY4 + (h /2);
cX6 = cX4;
cY6 = cY4 + h;
build();
}
I have created a class to draw this calliper on the screen, which it will do, however if I try to drag the calliper around the screen, it doesn't erase the original shape as I drag, so I get a long trail of shapes left behind. I thought I had omitted super.paintComponent(g)
from my paintComponent(Graphics g)
method, but even with it in there the code still does not work.
My drag method looks like this:
@Override
public void mouseDragged(MouseEvent ev)
{
double mx = ev.getX();
double my = ev.getY();
if (dragging)
{
calX = mx - offsetX;
calY = my - offsetY;
cal = setCalliper(calX, calY, calW, calH);
repaint();
}
}
If I change the line cal = setCalliper(calX, calY, calW, calH);
above to read cal = new Calliper(calX, calY, calW, calH);
then it works, but I have been told I shouldn't do it this way.
Any ideas why it doesn't work as expected?
Upvotes: 0
Views: 403
Reputation: 8348
The setCalliper()
directly calls the build method, a method which appends new points to all the previous points added to the Path2D
- so each time mouseDragged
is called more points are added to the Path. Try calling reset()
before calling build()
(or call reset in the build method before the moveTo/lineTo calls).
Upvotes: 1