[英]Why does getContentPane().getWidth() return 0?
我有一個擴展JFrame
Window
類和一個擴展JPanel
Content
類。 Content
對象添加到Window
對象。
類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();
}
}
課程Content
:
public class Content extends JPanel
{
public Content(Window w)
{
window = w;
System.out.println(window.getContentPane().getWidth());
}
}
現在,我需要知道內容窗格的寬度。 但是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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.