将MouseAdapter添加到JFrame

时间:2014-07-08 09:09:49

标签: java swing jframe mouselistener

我有一个MouseAdapter,用于通过单击其背景来拖动窗口,如下所示:

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);
}
}

简单,对吧?

然后我将它添加到JFrame我用它(我也在JDialogUE上使用它,因此' Window':

// Drag Listeners

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

拖动(当前)仅在构建新Dragger时有效,然后将其添加为 一个MouseListener和MouseMotionListener。

是否有一种更好,更漂亮,更优雅,更传统的声音,更专业的健壮,所以它只是用一种方法来做到这一点?

1 个答案:

答案 0 :(得分: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)

不确定它是否是一种好方法,但它占用的空间更少,并且如果你在install方法中添加更多检查,也可以确保不添加Dragger两次 - 当然如果你没有我想在同一个窗口安装Dragger两次。

同样在这种情况下,您不需要查看代码以了解此类的用法,因为您确定如何安装和卸载它,并且可以在一个位置更改该行为,而不是修改大量{{1调用。