Java 自定义 Path2D

Java custom Path2D

我创建了一个自定义 Path2D class 来在屏幕上绘制一个 H 形 "calliper",用于我正在做的项目。我想拖动并最终调整屏幕上的卡尺大小。我设法设置了 Path2D,这样我就可以绘制卡尺了,代码如下所示:

  1. 声明和构造函数:

    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();
    
    }
    
  2. build()方法(用于绘制路径)和setCalliper()方法,用于重新定义坐标,或者宽高:

    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();
    }
    

我创建了一个 class 来在屏幕上绘制这个卡尺,它会这样做,但是如果我尝试在屏幕上拖动卡尺,它不会在我拖动时擦除原始形状, 所以我留下了一长串形状。我以为我从我的 paintComponent(Graphics g) 方法中省略了 super.paintComponent(g),但即使在那里代码仍然不起作用。

我的拖动方法是这样的:

@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();
    }

}

如果我将上面的 cal = setCalliper(calX, calY, calW, calH); 行更改为 cal = new Calliper(calX, calY, calW, calH); 那么它就可以工作,但我被告知我不应该这样做。

知道为什么它没有按预期工作吗?

setCalliper() 直接调用构建方法,该方法将新点附加到所有以前添加到 Path2D 的点 - 所以每次 mouseDragged 被调用更多的点是添加到路径。尝试在调用 build() 之前调用 reset()(或者在 moveTo/lineTo 调用之前在构建方法中调用 reset)。