gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:29:05 24 4
gpt4 key购买 nike

我有一个扩展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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com