Moving undecorated window by clicking on JPanel

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

    I have a simple solution from my project. Here is my undecorated JDialog class.

    public class TimerDialog extends JDialog {
    // some fields here
    private Point mouseClickPoint; // Will reference to the last pressing (not clicking) position
    
    private TimerDialog() {
        initComponents();
        addEventsForDragging();
    }
    
    private void addEventsForDragging() {
        // Here is the code does moving
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                mouseClickPoint = e.getPoint(); // update the position
            }
    
        });
        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point newPoint = event.getLocationOnScreen();
                newPoint.translate(-mouseClickPoint.x, -mouseClickPoint.y); // Moves the point by given values from its location
                setLocation(newPoint); // set the new location
            }
        });
    }
    
    private void initComponents() {
        setLayout(new FlowLayout());
        // adding components
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setAlwaysOnTop(true);
        setUndecorated(true);
        setResizable(false);
        pack();
    }
    }
    

提交回复
热议问题