.pack() causes the components to be in the wrong place but works after window resize

我与影子孤独终老i 提交于 2019-12-14 02:35:03

问题


I am creating a game in java using Swing.

I am using

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

on my JFrame to start it as a maximized window.

After this I am using

mainJFrame.pack();

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.

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.

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.

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.

Thanks for your time.


回答1:


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.



来源:https://stackoverflow.com/questions/24239091/pack-causes-the-components-to-be-in-the-wrong-place-but-works-after-window-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!