我有一个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时起作用。

有没有更好,更漂亮,更优雅,更传统的声音,更专业的鲁棒性,那么,仅用一种方法就可以做到吗?

最佳答案

在这种情况下,我建议在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在同一窗口上安装了两次。

同样,在这种情况下,您无需查看代码来了解此类的用法,因为您可以确定如何安装和卸载该类,并且可以在一处更改该行为,而无需修改许多add*Listener调用。

关于java - 将MouseAdapter添加到JFrame,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24627911/

10-08 23:47