如何拖动多边形?

时间:2014-01-14 15:59:07

标签: java awt mouseevent polygon java-2d

我使用java.awt.Polygon在Java中绘制了一个多边形。我想用鼠标移动多边形(我想拖动它)。我知道我必须在mouseDragged中使用addMouseMotionListener方法。这样我就可以知道鼠标拖动多边形的路径的(x,y)坐标。

但问题是我不知道如何处理获取的(x,y)来移动多边形。这是代码的一部分:

public void mouseListeners(DrawEverything det) {
    det.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseDragged(java.awt.event.MouseEvent evt) {

            if( isMouseInMe(evt.getX(), evt.getY())){//this "if" checks if the cursor is in the shape when we drag it

                int xTmep , yTemp ;
                xTmep = (int) (evt.getX() - xMousePressed) ;//xMousePressed--> the x position of the mouse when pressed on the shape
                yTemp = (int) (evt.getY() - yMousePressed) ; 

                for(int i = 0 ; i < nPoints ; ++i){
                    xPoints[i]  +=    xTmep;//array of x-positions of the points of polygon
                    yPoints[i]  +=   yTemp;
                }
            }
        }
    });

这部分是我遇到问题的主要部分:

for(int i = 0 ; i < nPoints ; ++i){
    xPoints[i]  +=    xTmep;
    yPoints[i]  +=   yTemp;
}

1 个答案:

答案 0 :(得分:2)

看起来好像是将鼠标当前位置和多边形位置之间的差异添加到每个帧上多边形的新位置。你想要做的只是在上一次调用mouseDragged()时添加鼠标新位置与其位置之间的差异。

你可以很容易地做到这一点。在for循环后,添加以下内容:

xMousePressed = evt.getX();
yMousePressed = evt.getY();

然后在下次调用mouseDragged()时,它将更新多边形相对于其在前一帧中的位置的位置。