Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving a JFrame with custom title bar

How can I move a JFrame having a custom title bar?

I remove the default title bar and I did my own design. This is how it looks like:

enter image description here

I want to know how to drag a JFrame when the cursor is placed on the title bar only and not the whole frame. I've searched already and I have seen a lot of samples but I still don't get it. Do you guys have any simple code that I can understand?

I haven't started the code yet since I don't know how to start it. All I know is that, it is about mouseDragged or MouseMotionListener.

like image 203
Robert Avatar asked Jan 24 '26 07:01

Robert


1 Answers

I implemented the following:

public class DragFrame extends JFrame {

  int mpX, mpY;

  public DragFrame() {

    addMouseListener( new MouseAdapter() {
        @Override
        public void mousePressed( MouseEvent e ) {
          mpX = e.getX();
          mpY = e.getY();
        }
    } );

    addMouseMotionListener( new MouseMotionAdapter() {
        @Override
        public void mouseDragged( MouseEvent e ) {
          setLocation(
              getLocation().x + e.getX() - mpX,
              getLocation().y + e.getY() - mpY );
        }
    } );
  }
}

Thanks to @peeskillet for giving the crucial link to Drag and Resize undecorated JFrame with the inspiration to save the mouse position on mousePressed(...).

like image 128
Gerold Broser Avatar answered Jan 25 '26 20:01

Gerold Broser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!