java 如何设置JPanel大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3096037/
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
How to set JPanel size?
提问by chaz
I'm using Netbean's form creator and I'm trying out some things. I'm not sure if it's the layout manager, but when I create my own JPanel and add it to the main content pane of the my window, the size of the panel always maximizes inside the FrameView no matter what re-dimensioning methodology I use such as setSize or setPreferred size. I'm very new to AWT and Swing.
我正在使用 Netbean 的表单创建器,并且正在尝试一些东西。我不确定它是否是布局管理器,但是当我创建自己的 JPanel 并将其添加到我窗口的主内容窗格时,无论我使用什么重新调整尺寸方法,面板的大小总是在 FrameView 内最大化例如 setSize 或 setPreferred 大小。我对 AWT 和 Swing 很陌生。
回答by Xorty
With NetBeans WYSIWYG designer it's a peace of cake - just be sure to use Free Form Design and use mouse for resizing. Maybe the panel is itself larger than FrameView, so double click on it (you are editing it exclusively) and make it smaller. Than double click to get back to parent component and you should be fine.
使用 NetBeans WYSIWYG 设计器,这是一件轻而易举的事 - 只需确保使用自由形式设计并使用鼠标调整大小。也许面板本身比 FrameView 大,所以双击它(您正在专门编辑它)并将其缩小。比双击返回父组件,你应该没问题。
Or maybe check some tutorials at NetBeans site.
或者可以查看NetBeans 站点上的一些教程。
回答by Michael Borgwardt
You're not supposedto set sizes manually. Leave that to the layout managers, and your GUI will not break when the window size or the font or even just a button label changes.
您不应该手动设置尺寸。将它留给布局管理器,当窗口大小或字体甚至只是按钮标签发生变化时,您的 GUI 不会中断。
The trick with layout managersis that you can use not just one but several, in nested JPanels. That way, nearly any layout is possible.
布局管理器的诀窍在于,您不仅可以在嵌套的JPanels 中使用一个,还可以使用多个。这样,几乎任何布局都是可能的。
回答by Vanya
This happens because the layout manager of JPanel's container (perhaps it is either JFrame or another JPanel) instructs the JPanel to maximize.
发生这种情况是因为 JPanel 的容器(可能是 JFrame 或另一个 JPanel)的布局管理器指示 JPanel 最大化。
Do the following:
请执行下列操作:
Find out, who is the parent of this JPanel (take a look at NetBeans's containment object tree)
Check, what layout is defined for the container
Read the documentation about LayoutManager's (they're in java.awt package)
???
PROFIT!
找出谁是这个 JPanel 的父级(看看 NetBeans 的包含对象树)
检查,为容器定义了什么布局
阅读有关 LayoutManager 的文档(它们在 java.awt 包中)
???
利润!
回答by Brett
In my experience, Swing is a very picky thing. I'd try setMaximumSizeand setPreferedSize. As a side note though: when ever I used GridLayout, it always stretches whatever is in each of the cells (to make it symmetrical I guess). Flow, Box, Border, and I think GridBag don't have that problem though.
根据我的经验,Swing 是一个非常挑剔的东西。我会尝试setMaximumSize和setPreferedSize。不过作为旁注:当我使用 时GridLayout,它总是会拉伸每个单元格中的任何内容(我猜是为了使其对称)。Flow、Box、Border 和我认为 GridBag 没有这个问题。
-Brett
-布雷特

