Moving undecorated window by clicking on JPanel

前端 未结 6 806
鱼传尺愫
鱼传尺愫 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:50

    This code works very well with single monitor. It uses a simple mouselistener and mouse motion listener, which do some basic algebra do move the frame.

    class Frame extends JFrame{
    
        private int framePositionX, framePositionY, mousePositionX, mousePositionY, newMousePositionX, newMousePositionY;
    
        Frame(){
    
            addMouseListener(new MouseListener() {
                @Override
                public void mouseClicked(MouseEvent mouseEvent) {
                    framePositionX = mouseEvent.getComponent().getX();
                    framePositionY = mouseEvent.getComponent().getY();
                    mousePositionX = mouseEvent.getX();
                    mousePositionY = mouseEvent.getY();
                }
                @Override
                public void mousePressed(MouseEvent mouseEvent) {
                    framePositionX = mouseEvent.getComponent().getX();
                    framePositionY = mouseEvent.getComponent().getY();
                    mousePositionX = mouseEvent.getX();
                    mousePositionY = mouseEvent.getY();
                }
                @Override public void mouseReleased(MouseEvent mouseEvent) { }
                @Override public void mouseEntered(MouseEvent mouseEvent) { }
                @Override public void mouseExited(MouseEvent mouseEvent) { }
            });
    
            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    newMousePositionX = e.getX();
                    newMousePositionY = e.getY();
                    int newFramePositionX = (newMousePositionX - mousePositionX)+ framePositionX;
                    int newFramePositionY = (newMousePositionY - mousePositionY)+ framePositionY;
                    e.getComponent().setLocation(newFramePositionX, newFramePositionY);
                }
            });
    
            setUndecorated(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }
    }
    

提交回复
热议问题