3

My question is quite simple I guess ... I would like to have my java Frame centered when I run my program.

I used the following code :

    setLocationRelativeTo(null);

Problem :

This is the top left corner of the frame which is centred but not the entire frame. How can I correct this please, and having the full frame centred?

Thank you for your help!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1614914
  • 77
  • 2
  • 7

2 Answers2

9

setLocationRelativeTo(null); ... This is the top left corner of the frame which ...

It seems the call is being made at the wrong time, before the frame has assumed the natural size. To fix that, do it in this order.

  • Add all the components, to give the GUI a size.
  • Call pack() to cause the frame to become the minimum size needed to display the components it curently contains.
  • Call setLocationRelativeTo(null);

OTOH: If it is your program running on your computer, go with that. But if you need to provide the app. to other people like me, please consider using setLocationByPlatform(true) (Windows demo. below).

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • @gontard I think so too! But it is really up to the person that asked the question, to make the decision. When I posted this answer, there was already an accepted answer. But I hoped to inject some other ideas, earn a few up-votes, and maybe, ..just maybe, get the asker to change their mind. ;) – Andrew Thompson Aug 22 '12 at 13:04
  • Hello, I just read your answer and the other comments about it, and I must admit that your answer is the best one and easiest. I followed your advices and it works fine. Thank you, at least my code will be more "clean". – user1614914 Aug 22 '12 at 13:46
  • Sorry Dan, please do not take it bad, I didn't want to hurt you ... Thank you for your help anyway! – user1614914 Aug 22 '12 at 13:51
0

You can try this. It is working in my case.

Frame frame = new Frame("Centered Frame");
Dimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dimemsion.width/2-frame.getSize().width/2, 
                  dimemsion.height/2-frame.getSize().height/2);

If you are using NetBeans, go to platee manager -> property -> form Size policy.

Pang
  • 9,564
  • 146
  • 81
  • 122
manikant gautam
  • 3,521
  • 1
  • 17
  • 27