问题
Yesterday I ask a question about how to draw a bounding box to hold a shape inside and how to drag and drop that selected shape.
The first question is solved. But I'm having some trouble to move the shape. Is there any especific transformations to move a shape 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 return true in case of sucess. What I'm trying to do is to add the difference between the previous point of dragg and the actual.
When I run this code I have a problem:
The shape only goes to right/left, up and down is not working...
.
回答1:
int x = e.getX(), y = e.getX();
This should probably be changed to
int x = e.getX(), y = e.getY();
That's why it only works in the x direction, you aren't actually taking into account the Y direction
回答2:
Yes, in order to drag components you also need to know the starting location so you can calculate the distance the mouse has moved.
Here is some code that shows this general behaviour for moving a window.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class MoveWindow extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me)
{
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
private static void createAndShowGUI()
{
JWindow window = new JWindow();
window.setSize(300, 300);
window.setLocationRelativeTo( null );
window.setVisible(true);
MouseInputAdapter listener = new MoveWindow();
window.addMouseListener( listener );
window.addMouseMotionListener( listener );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
I'll let you implement it for your purposes.
来源:https://stackoverflow.com/questions/26564462/drag-moving-a-shape-around-jpanel