Centering the entire window Java

孤街浪徒 提交于 2019-11-28 09:08:43

问题


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!


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/12072719/centering-the-entire-window-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!