Home > Enterprise >  Make JFrame undraggable in Windows
Make JFrame undraggable in Windows

Time:09-17

I would like to make a JFrame undraggable (The user cannot move the window when click on the title bar and move the mouse).

Is it possible to do that in Windows?

import javax.swing.JFrame;

public class Test extends JFrame {
    
    public Test() {
        this.setResizable(false);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

I'm using Java 11 on Windows 10.

CodePudding user response:

You can't

Because the setBounds of a frame happens on frame peer. Check the WFramePeer code.

First, the class is package private. You cant @Override it and decorate setWhateverBounds methods.

Secondly, there is a lot of native methods.

Your only hope,

might be to use frame.setUndecorated(true) and create your own title bar without dragging functionality. But good luck on giving this title bar the native UI style.

CodePudding user response:

From another stackoverflow question:-

Add this to your code

private void formComponentMoved(java.awt.event.ComponentEvent evt) {                                    
       this.setLocationRelativeTo(null);
    }     

frame.addComponentListener(new java.awt.event.ComponentAdapter() {
                public void componentMoved(java.awt.event.ComponentEvent evt) {
                    formComponentMoved(evt);
                    frame.setLocation(frame.getX(),frame.getY());
                }
            });
  • Related