摆动:设置JFrame内容区域大小

问题描述:

我试图制作一个可用内容区域正好为500x500的JFrame。如果我这样做...摆动:设置JFrame内容区域大小

public MyFrame() { 
    super("Hello, world!"); 
    setSize(500,500); 
} 

...我得到一个窗口,其全尺寸500×500是包括标题栏等,在这里我真的需要一个窗口,其大小是一样的东西504x520占窗口边框和标题栏。我怎样才能做到这一点?

,你可以尝试两件事情: 1 - 一个黑客:

public MyFrame(){ 
JFrame temp = new JFrame; 
temp.pack(); 
Insets insets = temp.getInsets(); 
temp = null; 
this.setSize(new Dimension(insets.left + insets.right + 500, 
      insets.top + insets.bottom + 500)); 
this.setVisible(true); 
this.setResizable(false); 
} 

2或 添加一个JPanel在框架的内容窗格和 只需设置首选/最小尺寸的JPanel的 到500X500,呼叫包()

  • 2-是更便携

没关系,我想通了:

public MyFrame() { 
    super("Hello, world!"); 

    myJPanel.setPreferredSize(new Dimension(500,500)); 
    add(myJPanel); 
    pack(); 
} 
+2

在Java 5中,实际上可以在没有其他面板的情况下执行此操作。请参阅http://stackoverflow.com/questions/2796775/setting-the-size-of-a-contentpane-inside-of-a-jframe。 – 2010-05-09 10:19:11

只需使用:

public MyFrame() { 
    this.getContentPane().setPreferredSize(new Dimension(500, 500)); 
    this.pack(); 
} 

没有必要为一个JPanel是在那里,如果你只是想设置帧的大小。

+0

最简单的解决方案。 – 2013-03-22 03:31:03