Moving undecorated window by clicking on JPanel

Jan Kowalski picture Jan Kowalski · May 27, 2012 · Viewed 19.7k times · Source

Is there a possibility to move window by clicking on one of the panels in the window when that window is undecorated?

I have a main panel with matte border 40 pixels size, and few panels with controls inside, and I would like to move the window when clicking on that border. Is that possible?

Answer

Sorter picture Sorter · Nov 1, 2012

You can place another panel over the panel with the border, leaving the border visible.Use the following code to move your window.

public class MotionPanel extends JPanel{
    private Point initialClick;
    private JFrame parent;

    public MotionPanel(final JFrame parent){
    this.parent = parent;

    addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            initialClick = e.getPoint();
            getComponentAt(initialClick);
        }
    });

    addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {

            // get location of Window
            int thisX = parent.getLocation().x;
            int thisY = parent.getLocation().y;

            // Determine how much the mouse moved since the initial click
            int xMoved = e.getX() - initialClick.x;
            int yMoved = e.getY() - initialClick.y;

            // Move window to this position
            int X = thisX + xMoved;
            int Y = thisY + yMoved;
            parent.setLocation(X, Y);
        }
    });
    }
}

I've been working with this code for a while now to make a custom titlebar for undecorated windows. P.S.:You can generalize this example by extending JComponent instead of JPanel.