Domanda

I have drawn a polygon in Java using java.awt.Polygon. I want to move the polygon with mouse (I want to drag it). I know that I have to use mouseDragged method in addMouseMotionListener. That way I can know (x,y) coordinate of the path in which mouse is dragging the polygon.

But the problem is that I do not know what to do with the acquired (x,y) to move the polygon. This is a part of the code:

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

This part is the main part that I am having trouble with:

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

Soluzione

It looks as if you are adding the difference between the mouse's current position and the polygon's position to the polygon's new position on each frame. What you want to do is only add the difference between the mouse's new position and its position the last time that mouseDragged() was called.

You can do this fairly easily. After your for loop, add the following:

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

Then the next time mouseDragged() is called, it will update the polygon's position relative to its position in the previous frame.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top