Swing:设置JFrame内容区域大小

igu*_*222 21 java swing jframe

我正在尝试制作一个可用内容区域正好为500x500的JFrame.如果我这样做......

public MyFrame() {
    super("Hello, world!");
    setSize(500,500);
}
Run Code Online (Sandbox Code Playgroud)

...我得到一个全尺寸为500x500的窗口,包括标题栏等,我真的需要一个窗口,其大小类似于504x520,以便考虑窗口边框和标题栏.我怎样才能做到这一点?

rin*_*rer 26

你可以尝试几件事: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);
}
Run Code Online (Sandbox Code Playgroud)

2-或将JPanel添加到框架的内容窗格中,只需将JPanel的首选/最小尺寸设置为500X500,调用pack()

  • 2-更便携


小智 26

只需使用:

public MyFrame() {
    this.getContentPane().setPreferredSize(new Dimension(500, 500));
    this.pack();
}
Run Code Online (Sandbox Code Playgroud)

如果您只想设置帧的大小,则不需要JPanel.


igu*_*222 7

没关系,我明白了:

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

    myJPanel.setPreferredSize(new Dimension(500,500));
    add(myJPanel);
    pack();
}
Run Code Online (Sandbox Code Playgroud)

  • 在Java 5中,实际上可以在没有其他面板的情况下执行此操作.请参阅http://stackoverflow.com/questions/2796775/setting-the-size-of-a-contentpane-inside-of-a-jframe. (2认同)