布局和最小尺寸
我正在尝试将一个具有最小尺寸设置的新面板插入到现有表单中。不幸的是,在我这样做之后:(
this.add(scrap);
this.moveScrapCentre(scrap); // runs setLocation(...)
this.revalidate();
this.repaint();
其中this
:具有空布局的JPanel,scrap
:具有框布局和子项的JPanel)
scrap
被调整为(0,0)
- 尽管我在 Netbeans 的属性编辑器中设置了最小大小和首选大小。除了强制 scrap.setSize(scrap.getPreferredSize())
之外,如何防止这种情况发生?
I'm trying to insert a new panel with a minimal size set onto an existing form. Unfortunately after I do this:
this.add(scrap);
this.moveScrapCentre(scrap); // runs setLocation(...)
this.revalidate();
this.repaint();
(where this
: JPanel with null layout, scrap
: JPanel with box layout and children)
the scrap
gets resized to (0,0)
- even though I set both minimal and preferred size in Netbeans' property editor. How can I prevent this, apart from forcing scrap.setSize(scrap.getPreferredSize())
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“虽然我们强烈建议您使用布局管理器,但您也可以在没有它们的情况下执行布局。通过将容器的布局属性设置为 null,您可以使容器不使用布局管理器。使用这种称为绝对定位的策略,您必须指定大小和位置。绝对定位的一个缺点是,当调整顶级容器的大小时,它也不能很好地适应用户和系统之间的差异,例如不同的字体大小和区域设置。 "—设置布局管理器< /a>
附录:哎呀,我读错了问题。 即可
只需使用您想要的
w
和h
值 。如果this
是间隔符,则布局并不重要。附录:仔细观察,
scrap
的大小可能会动态变化。您可以相应地重写getPreferredSize()
。当您使用 GUI 设计器时,您的面板有一个类似如下的声明:您可以在类内部但在生成的代码折叠之外添加所需的方法:
另外:GUI 设计器是一个辅助假设了解底层布局管理器。 Noteing 要求您对每个面板都使用它,并且许多布局相当简单。我经常看到设计者将其用于需要更复杂布局的面板,例如
GroupLayout
和SpringLayout
。"Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales."—Setting the Layout Manager
Addendum: Oops, I misread the question. Just do
using your desired values of
w
andh
. Ifthis
is a spacer, the layout shouldn't matter.Addendum: Looking yet closer, the size of
scrap
may be changing dynamically. You can overridegetPreferredSize()
accordingly. As you're using the GUI designer, your panel has a declaration something like this:You can add the required method inside the class but outside the generated code fold:
Aside: The GUI designer is an aid that presumes an understanding of the underlying layout manager. Noting requires you to use it for every panel, and many layouts are fairly straightforward. I often see the designer's use reserved for panels needing more complex layouts such as
GroupLayout
andSpringLayout
.