动态添加 JPanel 时大小计算错误
我正在编写一个虚拟笔记本应用程序。这个想法是将具有各种内容(基于外部文件)的面板添加到充当页面的面板中。一旦该页面已满,其专用的 add 方法应该返回 false。
问题是,当我添加面板时,我不知道如何准确确定面板的大小,所以我最终添加了太多面板。面板的首选尺寸通常太短,并且尺寸的高度为 0。有没有办法确定组件在布局中占用的确切大小?
我尝试过使用 doLayout(),但它似乎没有改变我的组件的大小或preferredSize。也许是我使用方式不对?这是添加方法:(contentPanel 有 BoxLayout,内容面板没有设置大小,但被添加到具有设置大小的面板(this)。此方法所在的类扩展了 JPanel)
public boolean addSpecializedgPanel(SpecializedPanel sp) {
this.contentPanel.add(sp);
this.doLayout();
if (this.contentPanel.getSize().height > this.getHeight()) {
this.contentPanel.remove(sp);
return false;
}
return true;
}
感谢您的任何帮助(即使它批评我的整个设计:))!这一直是一个非常头疼的问题!
I am writing an application that is a virtual notebook. The idea is to have panels with various content (which is based on an external file) added to a panel that acts as a page. Once that page is full, its specialized add method should return false.
The problem is that I can't figure out how to accurately determine the size of the panels when I'm adding them, so I end up adding too many. The preferredSize of the panels is generally too short, and the size has 0 height. Is there a way to determine the exact size that a component is taking up in a layout?
I've tried using doLayout(), but it doesn't seem to change the size or preferredSize of my components. Maybe I'm not using it right? Here is the add method: (The contentPanel has BoxLayout, and the content panel doesn't have a set size, but is added to a panel (this) that does. The class this method is in extends JPanel)
public boolean addSpecializedgPanel(SpecializedPanel sp) {
this.contentPanel.add(sp);
this.doLayout();
if (this.contentPanel.getSize().height > this.getHeight()) {
this.contentPanel.remove(sp);
return false;
}
return true;
}
Thanks for any help (even if it criticizes my whole design :) )! This has been a huge headache!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你不应该处理这样的大小,你应该使用布局管理器。也许您应该看看如何使用CardLayout
I don't think you should deal with the size like that, you should use a layout manager for that. Maybe you should have a look at How to use CardLayout
您想在面板上使用 Container.validate() (可能首先调用 invalidate()):
这应该会导致布局发生,从而调整组件的大小。然后,在删除失败的面板后,您需要在返回 false 之前 invalidate() 。
You want to use Container.validate() on the panel (possibly calling invalidate() first):
This should cause layout to occur, and, consequently, resizing of the components. You will then need to invalidate() after removing your failing panel, before returning false.