Java – drag / move shapes around the JPanel
•
Java
Yesterday I asked a question about how to draw a bounding box to maintain the internal shape and how to drag and drop the selected shape
The first problem was solved But I had some trouble moving shapes Are there any specific transformations to move the shapes around the JPanel?
I have this Code:
public boolean drag(MouseEvent e) { if(points.isEmpty()) //if point's vector is empty return false; if(!selected) return false; int x = e.getX(),y = e.getX(); if (!dragging) lastMovePoint.setLocation(x,y); dragging = true; int deslocX = 0; int deslocY = 0; int oldX = -1; int oldY = -1; int size = points.size(); for(int i = 0; i < size; i++) { oldX = lastMovePoint.x; oldY = lastMovePoint.y; deslocX = x - oldX; deslocY = y - oldY; points.set(i,new Point(points.get(i).x + deslocX,points.get(i).y + deslocY)); //set the vector of points so that when there is a repaint() it repaints the shape with the new //coordinates } lastMovePoint.setLocation(x,y); //set the location of the old point return true; }
This method is called by the listener mousedragged and returns true on success What I want to do is add the difference between the previous drag point and the actual value
When I ran this code, I encountered a problem:
Shape only right / left, up and down do not work
.
Solution
int x = e.getX(),y = e.getX();
int x = e.getX(),y = e.getX();
This may be changed to
int x = e.getX(),y = e.getY();
That's why it works only in the X direction, and you don't actually think about the Y direction
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码