Java Swing:设置 JFrame 内容区域大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2451252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swing: set JFrame content area size
提问by igul222
I'm trying to make a JFrame with a usable content area of exactly 500x500. If I do this...
我正在尝试制作一个可用内容区域正好为 500x500 的 JFrame。如果我这样做...
public MyFrame() {
super("Hello, world!");
setSize(500,500);
}
... I get a window whose full size is 500x500, including the title bar, etc., where I really need a window whose size is something like 504x520 to account for the window border and titlebar. How can I achieve this?
...我得到一个完整大小为 500x500 的窗口,包括标题栏等,我真的需要一个大小为 504x520 的窗口来解释窗口边框和标题栏。我怎样才能做到这一点?
采纳答案by ring bearer
you may try couple of things: 1 - a hack:
你可以尝试几件事: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- or Add a JPanel to the frame's content pane and Just set the preferred/minimum size of the JPanel to 500X500, call pack()
2- 或将 JPanel 添加到框架的内容窗格并将 JPanel 的首选/最小尺寸设置为 500X500,调用 pack()
- 2- is more portable
- 2-更便携
回答by igul222
Never mind, I figured it out:
没关系,我想通了:
public MyFrame() {
super("Hello, world!");
myJPanel.setPreferredSize(new Dimension(500,500));
add(myJPanel);
pack();
}
回答by Michael
Simply use:
只需使用:
public MyFrame() {
this.getContentPane().setPreferredSize(new Dimension(500, 500));
this.pack();
}
There's no need for a JPanel to be in there, if you just want to set the frame's size.
如果您只想设置框架的大小,则无需在其中添加 JPanel。