java在jPanel周围拖动/移动形状
昨天我问了一个问题,关于如何绘制一个边界框来容纳一个形状,以及如何拖放选定的形状
第一个问题解决了。但我在移动形状上有点困难。有没有什么特殊的变换来移动一个形状在jPanel周围
我有这个密码:
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;
}
侦听器mouseDragged调用此方法,如果成功,则返回true。我想做的是,在之前的dragg点和实际的dragg点之间添加差异
运行此代码时,我遇到了一个问题:
形状只会向右/向左,上下不起作用
# 1 楼答案
这可能应该改为
这就是为什么它只在x方向起作用,而实际上没有考虑Y方向