java 在 BorderLayout.CENTER 中保留 JButton 的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/861659/
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
Preserving the size of a JButton in BorderLayout.CENTER
提问by Evan Fosmark
Is there a way of preserving the natural size of a JButton in the center of a BorderLayout? Right now, it expands in all directions to fill it up, but I want it normal size.
有没有办法在 BorderLayout 的中心保留 JButton 的自然大小?现在,它向各个方向扩展以填满它,但我希望它正常大小。
If it isn't possible, how can I get a button to be in the center of a panel with its normal size?
如果不可能,我怎样才能让按钮以正常大小位于面板的中心?
回答by Tom
The component in the center of a BorderLayout is always stretched, you can get round this by adding the button to a JPanel with a FlowLayout and then adding that into the CENTER.
BorderLayout 中心的组件总是被拉伸,您可以通过将按钮添加到带有 FlowLayout 的 JPanel,然后将其添加到 CENTER 来解决这个问题。
JPanel borderPanel = new JPanel(new BorderLayout());
JButton theButton = new JButton("Click Me");
JPanel flowPanel = new JPanel(new FlowLayout());
flowPanel.add(theButton);
borderPanel.add(BorderLayout.CENTER, flowPanel);
回答by Tom Hawtin - tackline
I suggest going straight for GridBagLayout. Although it has some odd behaviour and a bad interface, it's a standard layout that does pretty much everything. You are going to need it, so you might as well consistently use the same layout manager even when it is not strictly necessary.
我建议直接去GridBagLayout。虽然它有一些奇怪的行为和糟糕的界面,但它是一个标准布局,几乎可以做所有事情。您将需要它,因此即使不是绝对必要,您也可以始终使用相同的布局管理器。
回答by Keilly
Using a GridBagLayout for such a simple layouts are overkill. I would avoid GridBagLayout as much as possible - use a nested JPanel or MigLayout if you can (external jar)
将 GridBagLayout 用于如此简单的布局是多余的。我会尽可能避免使用 GridBagLayout - 如果可以,请使用嵌套的 JPanel 或 MigLayout(外部 jar)
回答by cd1
no matter what component you put in the center of a BorderLayout panel, it'll resize vertically and horizontally to fill all the available area. that's the characteristic of the center position.
无论您将什么组件放在 BorderLayout 面板的中心,它都会垂直和水平调整大小以填充所有可用区域。这就是中锋位置的特点。
回答by kgiannakakis
I think you can't do that with BorderLayout. The container's constraints will take priority over preferred sizes.
我认为你不能用 BorderLayout 做到这一点。容器的约束将优先于首选大小。
For manual coding I recommend to have a look at MiG Layout.
对于手动编码,我建议查看MiG Layout。

