我使用 JPanel 在屏幕上绘制一个正方形。 当我使用 MouseDragged 时,它工作得很好,几乎可以去到我想要的任何地方。每次我单击该正方形时,该正方形都会自动移动,并且左上角位于鼠标的正下方。 我应该如何做才能使正方形不会替换自身并保持在鼠标的正下方? 感谢您的帮助。
最佳答案
记下您所在组件的左上角
坐标之间的差异
移动和mousePressed
位置。
当您获得新位置时,只需减去该差值即可。
这里我尝试通过编码来解释它。让 myJPanel
成为您想要的组件
移动。那么这里是适合您的 MouseAdapter
。新位置存储在
newPosition
变量。
new MouseAdapter(){
int diffx = 0, diffy = 0;
public void mousePressed(MouseEvent e) {
Point topLeft = myJPanel.getLocation();
Point mouseDn = e.getPoint();
diffx = mouseDn.x - topLeft.x;
diffy = mouseDn.y - topLeft.y;
}
public void mouseDragged(MouseEvent e) {
Point mouseDr = e.getPoint();
int newX = mouseDr.x - diffx;
int newY = mouseDr.y - diffy;
Point newPosition = new Point(newX, newY);
}
};
关于java - 屏幕上的鼠标与 Dragndrop 上的 JPanel 之间的间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081058/