8

I have created a JFrame, and attempting to get it's size is giving an incorrect result, compared to what I expect.

I have determined that it is including the operating system borders around the edges, and the title bar.

How can I get/set the real size which I have available for rendering?

Ashley Davies
  • 1,873
  • 1
  • 23
  • 42
  • 1
    Are you sure it's a `JPanel` and not a `JFrame`? If it's the latter, use `frame.getContentPane().getSize()`. You may also find [this question](http://stackoverflow.com/questions/2796775/setting-the-size-of-a-contentpane-inside-of-a-jframe) useful... – Kevin K Aug 22 '11 at 23:13
  • Oh, sorry, yeah it was a JFrame. I can't beleive I got them mixed up. Apologies, I fixed the question. – Ashley Davies Aug 22 '11 at 23:23
  • *"it could be because I'm wording this wrongly"* It is more likely your entire approach is wrong. It is more common for a custom rendered component to ask 'how big am I?'. For anything else, the layouts should handle sizing automatically, without the app. ever asking for dimensions or sizes. – Andrew Thompson Aug 23 '11 at 08:24
  • The JPanel inside the JFrame returns 0, 0 as it's size. – Ashley Davies Aug 23 '11 at 11:49
  • _"The JPanel inside the JFrame returns 0, 0 as it's size."_ Probably the `JFrame` hasn't been made visible yet using `frame.setVisible(true)`. Before the frame is shown for the first time it returns (0, 0) for its size – Kevin K Aug 23 '11 at 20:10
  • For followers that desire to *set* the real content size (excluding title bar, etc.), see http://stackoverflow.com/questions/13474795/get-the-real-size-of-a-jframe-content – rogerdpack Dec 28 '12 at 18:58

2 Answers2

6

The size you are getting is the size of the content and the size of the insets. If you use Jcomponent.getInsets(), you can find the size of the content with simple subtraction.

Jeffrey
  • 44,417
  • 8
  • 90
  • 141
2

Your question is confusing: JPanels don't have title bars or window borders, they are abstract containers that are INSIDE JFrames. JFrames are the objects with title bars and window borders.

JPanel.getSize() should work as intended. However, for JFrames you'll want to use JFrame.getContentPane().getSize(), because getContentPane() returns the JPanel (which is the actual content area).

donnyton
  • 5,874
  • 9
  • 42
  • 60