2010-09-18 24 views
3

試圖拖動JPanel時出現問題。如果我在純粹的mouseDragged實現它爲:拖動JPanel

public void mouseDragged(MouseEvent me) { 
    me.getSource().setLocation(me.getX(), me.getY()); 
} 

我得到的移動物體在兩個位置之間彈跳所有的時間的一個奇怪的效果(產生更多的「拖」事件)。如果我這樣做是在this post描述的方式,而是用:

public void mouseDragged(MouseEvent me) { 
    if (draggedElement == null) 
     return; 

    me.translatePoint(this.draggedXAdjust, this.draggedYAdjust); 
    draggedElement.setLocation(me.getX(), me.getY()); 
} 

我得到的元素的彈跳少了很多的效果,但它仍然是可見的元素只有移動的鼠標指針的方式做½ 。爲什麼會發生這種情況/我該如何解決這種情況?

回答

1

試試這個

final Component t = e.getComponent(); 
    e.translatePoint(getLocation().x + t.getLocation().x - px, getLocation().y + t.getLocation().y - py); 

,並添加這個方法:

@Override 
public void mousePressed(final MouseEvent e) { 
    e.translatePoint(e.getComponent().getLocation().x, e.getComponent().getLocation().y); 
    px = e.getX(); 
    py = e.getY(); 
} 
+0

這樣,拖動的元素跳轉到窗口的左上角 - 但拖動至少是可以預測的... – viraptor 2010-09-20 01:21:21

+0

實際上 - 這在沒有鼠標壓縮翻譯的情況下工作。仍然不知道爲什麼。 – viraptor 2010-09-20 03:25:54

1

我不知道,您可以在使用的mouseDragged事件只是做。在過去,我使用mousePressed來保存原始點並拖動鼠標以獲取當前點。在這兩種情況下,我都會將點轉換爲屏幕上的位置。然後兩點之間的差異很容易計算出來,並且可以適當地設置位置。

我的這個通用類是Component Mover類。

+0

如果拖動導致查看區域滾動,您的方法(保存在屏幕上的位置)是否會中斷? – viraptor 2010-09-20 00:46:59

+0

必須承認我從來沒有嘗試在滾動窗格中拖動組件。 – camickr 2010-09-20 03:47:31

5

好的。老問題,但如果任何人遇到這個像我這樣做可以相對簡單地解決。對於在JFrame拖動JPanel我所做的:

@Override 
    public void mousePressed(MouseEvent e) { 
     if (panel.contains(e.getPoint())) { 
      dX = e.getLocationOnScreen().x - panel.getX(); 
      dY = e.getLocationOnScreen().y - panel.getY(); 
      panel.setDraggable(true); 
     } 
    } 

    @Override 
    public void mouseDragged(MouseEvent e) { 
     if (panel.isDraggable()) { 
      panel.setLocation(e.getLocationOnScreen().x - dX, e.getLocationOnScreen().y - dY); 
      dX = e.getLocationOnScreen().x - panel.getX(); 
      dY = e.getLocationOnScreen().y - panel.getY(); 
     } 
    } 

的關鍵是使用.getLocationOnScreen()並在mouseDragged每次通話結束更新調整。