gpt4 book ai didi

java - 在 JPanel 中间添加 JComponent

转载 作者:行者123 更新时间:2023-12-01 22:18:28 28 4
gpt4 key购买 nike

我想在 FlowLayout 和 GridBagLayout 之间进行权衡。简而言之,我需要在 JPanel 中添加一些组件(我不知道其中有多少,这是在运行时创建的),并且我希望这些组件能够垂直居中。FlowLayout 非常适合我的目标,但它在 JPanel 的顶部添加了组件。所以,我决定使用 GridBagConstraints,正如有人在这里建议的那样( Java layout manager vertical center ),但我对这个解决方案的问题是 GridBagLayout 不会自动创建新行,所以我只有一行(至少垂直居中!! !)我的组件插入的位置超出了屏幕尺寸。有人可以给我一些技巧吗???

最佳答案

I would like that these components to be center vertically. FlowLayout was ideal for my goal, but it adds components at the top of JPanel

您永远不会被迫使用单个面板或布局管理器。您可以使用嵌套面板。例如:

JPanel centered = new JPanel( choose your layout manager );

Box vertical = Box.createVerticalBox();
vertical.add( Box.createVerticalGlue() );
vertical.add( centered );
vertical.add( Box.createVerticalGlue() );
frame.add( vertical );

垂直面板中的胶水将占据等量的额外空间,从而使“居中”面板垂直居中。因此,您可以使用您想要的任何布局将组件添加到居中面板。

关于java - 在 JPanel 中间添加 JComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464466/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com