在我的画布上,我有圆 A 和圆 B。圆 A 将成为圆 B 的指定父级。我要开发的是两个形状之间的父子关系。因此,如果圆 A 在 X 轴上拖动 50 个单位,在 Y 轴上拖动 25 个单位,那么圆 B 也会这样移动。但是如果圈 B 被拖动,圈 A 将停留在最后一个位置。
我遇到的问题是重新拖动圆 A。从两个圆的初始位置,拖动圆 A 将相应地移动圆 B。但是一旦我释放鼠标并尝试再次拖动圆 A,圆 B 移动的单位数量比圆 A 的 x 位置多,而 y 单位的移动数量比圆 A 的 y 位置多。因此,每次我重新单击并拖动圆 A 时,每次按下鼠标按钮时,圆 B 都会以更远的距离递增到它自己的 x 和 y 轴上的新位置。
// initial positions of Circles (Part of Circle class which draws two circles)
int parentCirclePosX = 100;
int parentCirclePosY = 100;
int childCirclePosX = 103;
int childCirclePosY = 143;
public void mouseInput()
{
getCanvas().addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent event)
{
super.mouseReleased(event);
_cir.isDraggable = false;
Main.parentLabel.setText("Released " + _cir.isDraggable);
}
@Override
public void mousePressed(MouseEvent event)
{
super.mousePressed(event);
// Original mouse coordinates before dragging
last_x = _cir.getParentCircleX() - event.getX();
last_y = _cir.getParentCircleY() - event.getY();
// Child Circle's last position
lastChildx = _cir.getChildCircleX();
lastChildy = _cir.getChildCircleY();
int button = event.getModifiers();
// Check if mouse pointer is hovering over Parent Circle
boolean inXBounds = event.getX() > _cir.getParentCircleX() &&
event.getX() < _cir.getParentCircleX() + _cir.PARENT_CIRCLE_SIZE;
boolean inYBounds = event.getY() > _cir.getParentCircleY() &&
event.getY() < _cir.getParentCircleY() + _cir.PARENT_CIRCLE_SIZE;
if (button == InputEvent.BUTTON1_MASK && inXBounds && inYBounds)
{
_cir.isDraggable = true;
Main.parentLabel.setText("Pressed " + _cir.isDraggable);
}
getCanvas().repaint();
}
});
getCanvas().addMouseMotionListener(new MouseAdapter()
{
@Override
public void mouseDragged(MouseEvent event)
{
super.mouseDragged(event);
if (_bone.isDraggable)
{
updateLocation(event);
Main.parentLabel.setText(" Parent X: " + _cir.getParentCircleX() + " Y: " + _cir.getParentCircleY());
Main.childLabel.setText("Child X: " + _cir.getChildCircleX() + " Y: " + _cir.getChildCircleY());
}
getCanvas().repaint();
}
});
}
private void updateLocation(MouseEvent e)
{
_cir.setParentCircleX(last_x - _cir.PARENT_CIRCLE_SIZE / 2);
_cir.setParentCircleY(last_y - _cir.PARENT_CIRCLE_SIZE / 2);
_cir.setChildCircleX(lastChildx + e.getX() - 108 );
_cir.setChildCircleY(lastChildy + e.getY() - 108);
last_x = e.getX();
last_y = e.getY();
}