Search code examples
javaswingresize2d-games

Resize window and move contents within


I have a simple game I made in java. Essentially, my programming ability is relatively basic, and I would like to be able to resize the window the game is in and not have the images stay where they are and just display whiteness in the larger area. Here's a Screenshot. Is there any simple way to do this?


Solution

  • The two existing answers seem to presume you wish for the game space to resize.

    Resize the game space

    A game space that is a shoot'em'up does not necessarily resize well. E.G. When the game is twice as wide, should the left/right arrow presses move the ship twice as fast? Does stretching the window vertically increase gravity, or the speed of shots?

    Pad the game space

    The way I read the question, you simply wish to center the game space in the window. E.G.s of that can be seen in this answer.

    Fix the size of the top-level container.

    Many games fix the size to avoid the types of problems created by the 1st approach, and avoid the 'big blank bands' around the 2nd approach. This is as simple as calling setResizable(false).

    For this technique to work best:

    1. Ensure the component doing the game rendering has a preferred size set.
    2. Add it (and all other controls) to the frame.
    3. Call frame.pack() to ensure the frame is the right size to display the content.
    4. (Finally) call frame.setResizable(false).