Skip to main content

Swing Hack: Window Snapping

Posted by joshy on August 22, 2003 at 10:08 AM PDT

While working on another project I came up with a silly idea. How could I force windows to remain completely on screen and to snap to the screen edges? A simple form of window snapping. Since you can receive an event every time the window is moved it's easy to create a Component Listener to do it.

import java.awt.*;
import java.awt.event.*;

public class WindowSnapper extends ComponentAdapter {

    public WindowSnapper(int snap_distance) {
        this.sd = snap_distance;
    }

    private boolean locked = false;
    private int sd = 50;

    public void componentMoved(ComponentEvent evt) {
        if(locked) return;
        Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
        int nx = evt.getComponent().getX();
        int ny = evt.getComponent().getY();
        if(nx < 0) {
            nx = 0;
        }
        if(ny < 0) {
            ny = 0;
        }
        if(nx < 0+sd) {
            nx = 0;
        }
        if(nx > size.getWidth()-evt.getComponent().getWidth()-sd) {
            nx = (int)size.getWidth()-evt.getComponent().getWidth();
        }

        if(ny > size.getHeight()-evt.getComponent().getHeight()-sd) {
            ny = (int)size.getHeight()-evt.getComponent().getHeight();
        }
// make sure we don't get into a recursive loop when the
// set location generates more events
        locked = true;
        evt.getComponent().setLocation(nx,ny);
        locked = false;
    }
}

The code is nicely encapsulated as a listener. You can simply add it to whatever window you want to snap and the listener takes care of the rest. ex:
my_window.addComponentListener(new WindowSnapper(50));

Unfortunately, since you cannot intercept the move event, only
listen to it read only, you will end up with a somewhat ugly flashing effect as the window flips between where the cursor wants it to be and where the snapping wants it to be.

Related Topics >>