2013-03-05 106 views
0

我做了一個drag'n'drop算法,讓組件拖到窗口內。setLocation移動後的窗口

它表現良好,直到我移動框架窗口...

如果我移動窗口,該部件的位置,然後從等於I移動的幀當我點擊的距離的距離偏移它,當我拖動它。

任何人都知道爲什麼?

代碼示例:

public void mousePressed(final MouseEvent e) { 

    if(SwingUtilities.isLeftMouseButton(e)) { 

     origin = panel.getLocationOnScreen(); 

     panel.setLocation(origin.x, origin.y-panel.getHeight()/2); 

     view.add(panel, JLayeredPane.DRAG_LAYER); 
    } 

} 

public void mouseDragged(MouseEvent e) { 

    if(SwingUtilities.isLeftMouseButton(e)) { 

     panel.setLocation(e.getLocationOnScreen().x - panel.getWidth()/2, e.getLocationOnScreen().y - panel.getHeight()/2); 

    } 

} 
+0

我預計'e.getLocationOnScreen()'給全局座標,而'panel.setLocation(...)'使用相對座標。但這並不能解釋它爲什麼在第一個地方工作... – 2013-03-05 14:15:11

+0

@Heuster,你會知道如何將setLocation轉換爲全局座標? – 2013-03-05 14:34:44

回答

0

假設鼠標事件是由在其中面板應該被拖動,則應該只使用相對座標的容器上升。

也就是說,使用

public void mouseDragged(MouseEvent e) { 
    if(SwingUtilities.isLeftMouseButton(e)) { 
     panel.setLocation(e.getPoint().x - panel.getWidth()/2, e.getPoint().y - panel.getHeight()/2); 
    } 
}