Centering the entire window Java

后端 未结 2 1718
一生所求
一生所求 2020-12-21 06:13

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 :

    setLocatio         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-21 07:05

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

提交回复
热议问题