.pack()导致组件放置在错误的位置,但是在调整窗口大小之后可以工作 [英] .pack() causes the components to be in the wrong place but works after window resize

查看:120
本文介绍了.pack()导致组件放置在错误的位置,但是在调整窗口大小之后可以工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swing在Java中创建游戏.

I am creating a game in java using Swing.

我正在使用

mainJFrame.setExtendedState(mainJFrame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

在我的JFrame上将其作为最大化窗口启动.

on my JFrame to start it as a maximized window.

此后我正在使用

mainJFrame.pack();

能够获得正确的x& GUI中组件的y坐标.我需要这些坐标,因为我正在将自定义图像绘制到GUI.到目前为止,一切都很好.

to be able to get the correct x & y coordinates of components in the GUI. I need those coordinates since i'm painting custom images to the GUI. So far everything is fine.

当用户通过某个级别时,我将重建GUI以将其更新为新的级别设置,然后再次调用pack().

When a user has passed a level, i rebuild the GUI to updated it to the new level settings and then i call pack() again.

在调用pack()时,组件放置在错误的位置,略低于应有的位置.

When calling pack() the components are placed in the wrong place, slightly below where they are supposed to be.

但是,手动调整窗口大小会导致组件再次移到正确的位置.

However, manually resizing the window causes the components to go to the right place again.

我尝试在pack()之后调用mainJFrame.revalidate()mainJFrame.repaint(),但这没有效果.

I have tried calling mainJFrame.revalidate() and mainJFrame.repaint() after the pack() but this gives no effect.

如果需要,我可以提供打印屏幕和代码.

If needed I can supply printscreens and code.

感谢您的时间.

推荐答案

手动调整窗口大小可验证封闭容器及其所有子组件.为避免您描述的影响,在添加组件并调用pack()之后,仅在 后调用setVisible().您可以在此处找到更多相关建议.如果问题仍然存在,请编辑您的问题,以包含显示问题的 mcve .

Manually resizing the window validates the enclosing container and all of its subcomponents. To avoid the effect you describe, call setVisible() only after you have added components and invoked pack(). More related suggestions may be found here. If the problem persists, please edit your question to include an mcve that exhibits the problem.

这篇关于.pack()导致组件放置在错误的位置,但是在调整窗口大小之后可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆