Ragnarsson
Ragnarsson

Reputation: 1746

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

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.

Upvotes: 1

Views: 149

Answers (1)

trashgod
trashgod

Reputation: 205805

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.

Upvotes: 1

Related Questions