Search code examples
javaswingjframecontentpane

Why does getContentPane().getWidth() return 0?


I have a class Window that extends JFrame and a class Content that extends JPanel. An object of Content is added to an object of Window.

Class Window:

public class Window extends JFrame
{   
    private Content content;

    public Window()
    {       
        setTitle("My Window");
        setSize(800, 600);
        setResizable(false);
        setLocationRelativeTo(getParent());
        setDefaultCloseOperation(EXIT_ON_CLOSE);        

        content = new Content(this);

        add(content);

        setVisible(true);
    }

    public static void main(String[] args)
    {
        new Window();
    }
}

Class Content:

public class Content extends JPanel
{
    public Content(Window w)
    {
        window = w;

        System.out.println(window.getContentPane().getWidth());
    }
}

Now I need to know the width of the content pane. But window.getContentPane().getWidth() returns 0.

Can you tell me why?


Solution

  • Using SetPreferredSize() then using Pack() is the key before trying to call getWidth(). This code is just your code with small modification, and it works fine.

    public class Window extends JFrame
    {   
        private Content content;
    
        public Window()
        {       
            setTitle("My Window");
            setPreferredSize(new Dimension(800, 600));
    
            setResizable(false);
            setLocationRelativeTo(getParent());
            setDefaultCloseOperation(EXIT_ON_CLOSE);        
            pack();
    
            content = new Content(this);
    
            add(content);
    
            setVisible(true);
        }
    
        public static void main(String[] args)
        {
            new Window();
        }
    }
    public class Content extends JPanel
    {
        Window window = null;
        public Content(Window w)
        {
            window = w;
            System.out.println(window.getContentPane().getWidth());
        }
    }