How to get real JPanel Size?

39,806

Solution 1

The size will be 0,0 until it is displayed because the components and layout are not calculated beforehand.

Solution 2

thePanel.getSize();

This returns the Dimension.

I sometimes add a ComponentListener to show the dimension when the panel is resized.

EDIT: If you want the size of the content pane of the JFrame then

theFrame.getContentPane().getSize();
Share:
39,806
Yoda
Author by

Yoda

If you have a question about Bonjour in .NET and AXIS SDK I am the guy. I HATE telerik.

Updated on August 18, 2020

Comments

  • Yoda
    Yoda over 3 years

    How should I get real JPanel size in JFrame?

    • Andrew Thompson
      Andrew Thompson over 11 years
      "By really calling getSize()." It is possible that the method is being called prior to when it becomes realized. For more specific advice, post an SSCCE.
    • km1
      km1 over 11 years
      As @Andrew says. But you can't do it until its been rendered.
  • Yoda
    Yoda over 11 years
    It does not give real size java.awt.Dimension[width=0,height=0] I used that before
  • MadProgrammer
    MadProgrammer over 11 years
    @RobertKilar km half answered you question, add a ComponentLsterner to the panel you're interested in & monitor the componentResized event
  • km1
    km1 over 11 years
    @RobertKilar you're probably getting the size before its rendered. Try the component listener's resize event handler.
  • Sakkeer Hussain
    Sakkeer Hussain over 6 years
    Is there any call back for initialising child components of jPanel after it got its real width and height?
  • Cardinal System
    Cardinal System over 3 years
    Is there a way to force the layout to calculate component locations and sizes without calling setVisible(true)?
  • Cardinal System
    Cardinal System over 3 years
    @SakkeerHussain if you queue a runnable with SwingUtilities#invokeLater(java.lang.Runnable) after calling setVisible(true) on your JFrame, then that runnable will be executed after the panel is assigned its size. With this method, however, you will have to initialize your panel beforehand and update it after it's actually visible.