java - 为什么 getContentPane().getWidth() 返回 0?

标签 java swing jframe contentpane

我有一个扩展JFrame的类Window和一个扩展JPanel的类ContentContent 对象被添加到 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();
    }
}

内容:

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

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

现在我需要知道内容 Pane 的宽度。但是 window.getContentPane().getWidth() 返回 0。

你能告诉我为什么吗?

最佳答案

在尝试调用 getWidth() 之前,先使用 SetPreferredSize() 然后使用 Pack() 是关键。这段代码只是您的代码,稍加修改,就可以正常工作。

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());
    }
}

关于java - 为什么 getContentPane().getWidth() 返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481059/

相关文章:

正则表达式

java - JTextField 一次只允许一个字母?

java - 在从 JTextField 读取之前等待键

java - JFrame 的边框布局定位不符合预期

java - 该程序的 KeyAdapter 部分出错

java - SpringBoot 未加载使用 OpenAPI 3.0 生成的 Controller

java - 为什么 test1() 比 test2() 运行得快得多?

java - 边界内的抛物线

java - Swing:马拉雅拉姆语字符串无法在 JFrame 中正确呈现

java - 为什么我们在java main方法中将args[]命名为arhs[](或任何其他名称)就没有错误?