Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving undecorated window by clicking on JPanel

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?

like image 632
Jan Kowalski Avatar asked May 27 '12 11:05

Jan Kowalski


1 Answers

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.

like image 57
Sorter Avatar answered Oct 23 '22 17:10

Sorter