Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

swing - Centering the entire window Java

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...