Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - How to get the EXACT middle of a screen, even when re-sized

Ok, this sort of have 2 parts of the question.

  1. When I make a JFrame, and draw something on it, even if I make the width 400, and make it so that when an item hits it (Allowing for an items width, of course) It bounces back. But it always goes about 10 pixels off the screen for some reason. Is there a way to fix it, or do I just need to compensate by add/subtracting numbers?

  2. How can I get the EXACT screen center. So, if I make a JFrame which is default as 200*200 pixels, then the center would be 100*100. (Allowing for the problem in question 1) But if someone resizes the screen (and yes, I want them to be able to re-size it) the point is still the center. so if they make it full screen and their screen size is 1200*900, then the center would be 600*450.

I hope this is clear enough

Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

From the sounds of what you are saying, I think you misunderstand what the dimensions of a normal (decorated) frame include.

A JFrame consists of a window/frame (normally decorated with a border), a JRootPane, which contains a JLayeredPane which contains the content pane, JMenuBar and glass pane.

enter image description here

This is, one of the, reasons why you should never override a top level containers paint method, because you won't actually be painting within the content/view area.

So, the actual "paintable" region of a frame is it's width - border.width x height - border.height

enter image description here

The red line indicates the frame, the blue indicates the content pane.

This raises a very important question, where's the center of the frame? From the frames perspective, it's 100x100, but from the content pane's perspective, it's 92x81. Depending on what you want, will depend on which value you will use. For positioning the frame, you will want to to use the frames center point, for painting, your will want to use the content panes.

Now, the easiest way to center a frame on the screen is simply to call Window#setLocationRelativeTo(null) otherwise, I would suggest you use Timr's solution ;)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...