【问题标题】:How to drag a polygon?如何拖动多边形?
【发布时间】:2014-02-02 18:33:54
【问题描述】:

我使用java.awt.Polygon 在 Java 中绘制了一个多边形。我想用鼠标移动多边形(我想拖动它)。我知道我必须在addMouseMotionListener 中使用mouseDragged 方法。这样我就可以知道鼠标拖动多边形的路径的 (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;
}

【问题讨论】:

    标签: java awt mouseevent polygon java-2d


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多