Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JFrame set location at center of window on MAC OSX

Any body please can please help me, how to center a JFrame on Mac. OS X?

I have tried:

this.setLocationRelativeto(null);

this.setLocationRelativeto(this);
this.setLocationRelativeto(getRootPane());

..and

    final Toolkit toolkit = Toolkit.getDefaultToolkit();
    final Dimension screenSize = toolkit.getScreenSize();
    final int x = (screenSize.width - this.getWidth()) / 2;
    final int y = (screenSize.height - this.getHeight()) / 2;
    this.setLocation(x, y);

None of the above worked, my frame is still at the bottom and hidden behind the Mac dock.

like image 993
Asghar Avatar asked Oct 28 '25 06:10

Asghar


1 Answers

Location should be set after you packed your frame (wich calculates size of the frame). And after that it should be made visible (it is hidden by default otherwize).

 pack();
 setLocationRelativeTo(null);
 setVisible(true);
like image 196
yggdraa Avatar answered Oct 31 '25 00:10

yggdraa