2014-07-08 103 views
1

我有,我用它來點擊它的背景周圍簡單地拖動窗口,像這樣一個MouseAdapter:添加MouseAdapter到一個JFrame

public class Dragger extends MouseAdapter{ 

private Point offset; 
private Window window; 

public Dragger(Window w){ 
    window = w; 
} 

@Override 
public void mousePressed(MouseEvent e){ 

    offset = e.getPoint(); 
} 

@Override 
public void mouseDragged(MouseEvent e){ 

    Point m = e.getLocationOnScreen(); 

    window.setLocation(m.x - offset.x, m.y - offset.y); 
} 
} 

這麼簡單吧?

我把它添加到我使用它(我使用它在JDialogUE以及JFrame中,因此「窗口」:

// Drag Listeners 

    Dragger dr = new Dragger(this); 
    addMouseListener(dr); 
    addMouseMotionListener(dr); 

的阻力(目前)只有當工作我建立一個新的牽引,然後將其添加爲一個的MouseListener和的MouseMotionListener。

是否有剛剛做的更好,更漂亮,更優雅,更傳統的聲音,更專業穩健,如此這般,方式一種方法?

回答

1

在這種情況下,我建議Dragger類中編寫的輔助靜態方法:

public class Dragger extends MouseAdapter 
{ 
    private Point offset; 
    private Window window; 

    public Dragger (final Window w) 
    { 
     window = w; 
    } 

    @Override 
    public void mousePressed (final MouseEvent e) 
    { 
     offset = e.getPoint(); 
    } 

    @Override 
    public void mouseDragged (final MouseEvent e) 
    { 
     final Point m = e.getLocationOnScreen(); 
     window.setLocation (m.x - offset.x, m.y - offset.y); 
    } 

    public static void install (final Window window) 
    { 
     final Dragger dr = new Dragger (window); 
     window.addMouseListener (dr); 
     window.addMouseMotionListener (dr); 
    } 

    public static void uninstall (final Window window) 
    { 
     for (final MouseListener mouseListener : window.getMouseListeners()) 
     { 
      if (mouseListener instanceof Dragger) 
      { 
       window.removeMouseListener (mouseListener); 
      } 
     } 
     for (final MouseMotionListener mouseMotionListener : window.getMouseMotionListeners()) 
     { 
      if (mouseMotionListener instanceof Dragger) 
      { 
       window.removeMouseMotionListener (mouseMotionListener); 
      } 
     } 
    } 
} 

然後只需撥打Dragger.install(window)Dragger.uninstall(window)

不確定這是否是一種好方法,但佔用更少的空間,並且可能還會確保您不會添加Dragger兩次,如果您向install方法中添加更多檢查 - 當然如果您不想要在同一個窗口上安裝兩次Dragger

同樣在這種情況下,您不需要在代碼中查看此類的用法,因爲您確定如何安裝和卸載它,並且可以在一個位置更改該行爲,而不是修改大量add*Listener調用。