问题
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