Java自定义Path2D

时间:2015-03-20 18:57:34

标签: java graphics drawing drag path-2d

我创建了一个自定义Path2D类来在屏幕上绘制一个H形“卡尺”,用于我正在做的项目。我想拖动并最终调整屏幕上的卡尺。我已设法设置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();
    }
    
  3. 我已经创建了一个类来在屏幕上绘制这个卡尺,但是如果我尝试在屏幕上拖动卡尺,它就不会在我拖动时擦除原始形状,所以我得到一个长的留下的形状的痕迹。我以为我已经从super.paintComponent(g)方法中省略了paintComponent(Graphics 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);,那么它可以正常工作,但我被告知我不应该这样做。

    为什么它没有按预期工作的任何想法?

1 个答案:

答案 0 :(得分:1)

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