如何设置 JFrame 大小以适合 CardLayout 显示的 JPanel?
我有一个 JFrame
,其中包含 CardLayout
中的一组 JPanels
。每个 JPanel
都有不同的大小,我希望 JFrame
适应当前显示的 JPanel
的大小(而不是 JPanel< /code> 以适应
JFrame
的大小)。
我怎样才能实现这个目标?
I have a JFrame
containing a set of JPanels
in a CardLayout
. Each JPanel
has a different size and I want the JFrame
to adapt to the size of the currently displayed JPanel
(not the JPanel
to adapt to the size of the JFrame
).
How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般情况是:如果您遇到布局问题,始终使用适当的 LayoutManager 来解决它。 永远不要调整组件的大小提示来达到您的目标。
在这种情况下,调整CardLayout就特别容易了。默认情况下,它计算其 prefSize 为所有卡的 prefSizes 的最大值。只需子类化并实现即可返回当前可见卡的 prefSize(加上插图):
使用该方法(借用@mKorbel 的示例),main 方法可以干净地缩小:
The general is: if you have a layout problem, always solve it with an appropriate LayoutManager. Never tweak a component's sizing hint to reach your goal.
In this case, it's particularly easy to adjust the CardLayout. By default, it calculates its prefSize to the max of prefSizes of all cards. Simply subclass and implement to return the prefSize (plus insets) of the currently visible card:
Using that (borrowing @mKorbel's example), the main method cleanly shrinks down:
这是SSCCE。
1)对于尺寸的连续增加/减小,您应该寻找一些动画API。
或
2) 如果没有任何后台任务输出到 GUI,您可以在调整
JFrame
大小时暂停。在这种情况下,您可以通过使用包装在Runnable
线程中的Thread#sleep(int)
来延迟增加/减少。3) 注意(不适用于 OP)在 EDT 期间直接使用 Thread#sleep(int) 将会冻结 GUI,直到延迟结束。
Here is the SSCCE.
1) For continuous increase/decrease of size, you should look for some animation API.
or
2) If isn't there any background task with output to the GUI, you can to pause while sizing the
JFrame
. In that case, you would delay the increase/decrease by usingThread#sleep(int)
wrapped intoRunnable
thread.3) Notice (not for OP) using
Thread#sleep(int)
directly during EDT would be freeze GUI until the delay ended.我认为您可能使用了错误的布局管理器来执行您想要执行的操作(暂且不说,我不确定您是否想要执行您所说的操作)。
我还没有找到关于我怀疑的内容的文档,即 CardLayout 将其所有子级的大小调整为其容器的大小。我确实找到了对其“layoutContainer”方法的以下评论:
我认为这是合理的行为,因为对于用户来说,在遍历面板时让面板大小跳跃会非常烦人。
如果这确实是您想要的行为,那么我认为您需要一个不同的布局管理器。由于这对于 UI 来说通常是不寻常的行为,因此您很可能找不到标准的 UI 来执行此特定“功能”,因此您可能必须编写自己的 UI。
I think you may have the wrong layout manager for what you want to do (leaving aside, for the moment, that I am not sure you want to do what you say you want to do).
I have not yet found documentation on what I suspect, which is that CardLayout resizes all of its children to the size of its container. I did find the following comment for its "layoutContainer" method:
I think this is reasonable behavior, since it would be very annoying for a user to have the panel size jump around as panels are traversed.
If this is really the behavior you want, then I think you want a different layout manager. And since it is unusual behavior for a UI in general, you may well not find a standard one to do this particular 'feature', so you may have to write your own.