如何拖动多个选定对象并在框架内移动?
当前的实现是每当用户点击对象时,通过按SHIFT键,每个新对象都会被添加到 multiShape
但是,我只能移动单个选定的对象。
我的代码在这里:
public void mouseClicked(MouseEvent clickEvent) {
clickShape = null;
int x = clickEvent.getX(); // x-coordinate of point where mouse was
// clicked
int y = clickEvent.getY(); // y-coordinate of point
if (clickEvent.isShiftDown()) {
int top = shapes.size();
for (int i = 0; i < top; i++) {
Shape s = (Shape) shapes.get(i);
if (s.containsPoint(x, y)) {
s.setColor(Color.RED);
multiShape.add(s);
}
}
repaint();
}
}
}
我在Abstract Shape类下定义的移动对象如下:
void moveTo(int x, int y) {
left += x;
top += y;
}
mouseclick事件:
public void mousePressed(MouseEvent clickEvent) {
if (dragShape != null) {
return;
}
int x = clickEvent.getX(); // x-coordinate of point
int y = clickEvent.getY(); // y-coordinate of point
clickShape = null;
for (int i = shapes.size() - 1; i >= 0; i--) { // check shapes from
// front to back
Shape s = (Shape) shapes.get(i);
if (s.containsPoint(x, y)) {
dragShape = s;
prevDragX = x;
prevDragY = y;
clickShape = s;
break;
}
}
// Continue from here
if (clickShape == null) {
return;
} else if (clickEvent.isPopupTrigger()) {
click.show(this, x - 10, y - 2);
} else {
dragShape = clickShape;
prevDragX = x;
prevDragY = y;
}
}
public void mouseDragged(MouseEvent clickEvent) {
// User has moved the mouse. Move the dragged shape by the same
// amount.
if (dragShape == null) {
return;
}
int x = clickEvent.getX();
int y = clickEvent.getY();
if (dragShape != null) {
dragShape.moveTo(x - prevDragX, y - prevDragY);
prevDragX = x;
prevDragY = y;
repaint(); // redraw canvas to show shape in new position
}
}
public void mouseReleased(MouseEvent clickEvent) {
// User has released the mouse. Move the dragged shape, then set
// shapeBeingDragged to null to indicate that dragging is over.
if (dragShape == null) {
return;
}
int x = clickEvent.getX();
int y = clickEvent.getY();
if (clickEvent.isPopupTrigger()) {
click.show(this, x - 10, y - 2);
// } else {
dragShape.moveTo(x - prevDragX, y - prevDragY);
if (dragShape.left >= getSize().width || dragShape.top >= getSize().height
|| dragShape.left + dragShape.width < 0 || dragShape.top + dragShape.height < 0) { // shape
shapes.remove(dragShape); // remove shape from list
}
repaint();
}
dragShape = null;
}
答案 0 :(得分:0)
你只是将moveTo调用到一个名为dragShape的形状,这是你在这里得到的最后一个形状
for (int i = shapes.size() - 1; i >= 0; i--) { // check shapes from
// front to back
Shape s = (Shape) shapes.get(i);
if (s.containsPoint(x, y)) {
dragShape = s;
prevDragX = x;
prevDragY = y;
clickShape = s;
break;
}
}
而不是:
if (dragShape != null) {
dragShape.moveTo(x - prevDragX, y - prevDragY);
执行:
for (Shape s : multiShape)
s.moveTo(x - prevDragX, y - prevDragY);