我可以在显示之前获得正确的 JComponent 大小吗?

发布于 2024-11-30 11:44:06 字数 138 浏览 0 评论 0原文

JComponent 的大小何时计算?在屏幕上显示之后还是之前? 如果我在 .setVisible(true) 之前发送 .getSize() 消息,它会给我正确答案吗? 谢谢

When is the size of the JComponent is calculated? After being shown in the screen or before that?
if I send .getSize() message before .setVisible(true), would it give me the right answer?
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我很坚强 2024-12-07 11:44:06

例如,我有时会在调试时检查组件的大小,以找出为什么我看不到它们。在大多数情况下,尺寸将在 GUI 渲染后实现。渲染。当在顶级窗口上调用 pack()setVisible(true) 时,可能会发生这种情况。我通常的方法调用顺序是首先调用 pack() 因为这告诉布局管理器布置它们负责的组件,并设置组件和 GUI 的大小,然后调用setLocationRelativeTo(null) 将我的 GUI 居中,然后调用 setVisible(true) 来显示它。

I sometimes check the sizes of my components when debugging to find out why I can't see them for instance. In most cases, the sizes will be realized when the GUI has been rendered. This can occur when pack() or setVisible(true) has called on the top-level window. My usual sequence of method calls is to call pack() first as this tells the layout managers to lay out the components that they are responsible for, and sets the sizes of the components and the GUI, then call setLocationRelativeTo(null) to center my GUI, then call setVisible(true) to display it.

墨落成白 2024-12-07 11:44:06

布局管理器负责确定组件的大小,因此在将组件添加到框架并且框架已被 pack()ed or 使可见之前,您不知道其实际大小。

如果您使用尊重组件首选尺寸的布局管理器,那么您可以使用:

component.getPreferredSize();

为什么您认为您需要知道尺寸?一般来说,您不必担心尺寸,让布局管理器完成其工作。

The layout manager is responsible for determining the size of a component, so you don't know its actual size until the component has been added to the frame and the frame has been pack()ed ore made visible.

If you use a layout manager that respects the preferred size of a component then you can use:

component.getPreferredSize();

Why do you think you need to know the size? Generally you don't worry about sizes and let the layout manager do its job.

勿挽旧人 2024-12-07 11:44:06

除了通常的 pack() > setVisible(true) > > getPreferredSize() 序列,您可以validate() 相关Container来预览几何图形,如图此处

In addition to the usual pack() > setVisible(true) > getPreferredSize() sequence, you can validate() the relevant Container to preview the geometry, as shown here.

冰火雁神 2024-12-07 11:44:06

如果我理解正确的话,您想知道组件大小的原因是在用户单击“更多选项”按钮后重置 JWindow 的大小,不是吗?
我建议执行以下操作:当用户单击该按钮时,更新您的 UI,添加额外的组件,并在 JWindow 上执行 pack()。它应该调整到合适的大小。

If I understand properly, the reason why you want to know the size of a component is to reset the size of a JWindow once a user click on the "More options" button, isn't it?
I would suggest to do the following: when the user clicks on that button, update your UI adding the extra component, and the execute pack() on the JWindow. It should resize to the proper size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文