Moving undecorated window by clicking on JPanel

前端 未结 6 799
鱼传尺愫
鱼传尺愫 2021-02-08 15:43

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 siz

6条回答
  •  执笔经年
    2021-02-08 16:36

    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.

提交回复
热议问题