1

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ragnarsson
  • 1,736
  • 2
  • 11
  • 16
  • 3
    For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). – Andrew Thompson Jun 16 '14 at 08:07
  • This is because `pack()` tries to shrink your objects to a minimum size. Try using setPreferredSize instead :) – Pphoenix Jun 16 '14 at 08:08
  • 5
    @Pphoenix See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Jun 16 '14 at 08:09
  • @AndrewThompson My questions is, what can be done to stop the components to be placed in the wrong place? Working on posting an MCVE. – Ragnarsson Jun 16 '14 at 08:12
  • 2
    @Chrippe what I am thinking is, its not `pack()`. The problem is in your layout. So as Andrew suggested, post an MCVE. – Arijit Jun 16 '14 at 08:21

1 Answers1

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045