이동하고 mousePressed
위치의 구성 요소의 좌표 top-left
사이의 차이를 고려하십시오.
그리고 새로운 포지션을 얻으면 그 차이를 빼면됩니다.
여기서는 코딩을 통해 설명하려고했습니다. 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);
}
};