3

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Asghar
  • 2,336
  • 8
  • 46
  • 79
  • 1
    See also [How to best position Swing GUI's](http://stackoverflow.com/a/7143398/418556) & [What is the best practice for setting JFrame locations in Java?](http://stackoverflow.com/a/7778332/418556). Note that neither of those answers involves centering the GUI on screen. There are better alternatives. – Andrew Thompson Mar 30 '12 at 04:12

1 Answers1

8

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);
yggdraa
  • 2,002
  • 20
  • 23