我有一个扩展JFrame
的类Window
和一个扩展JPanel
的类Content
。 Content
对象被添加到 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/