Which containers / graphics components to use in a simple Java Swing game?

I'm creating a simple labyrinth game with Java + Swing. The game draws a randomized labyrinth on the screen, places a figure in the middle, and the player is then supposed to find the way out by moving the figure with arrow-keys. As for now, I'm using a plain background and drawing the walls of the labyrinth with Graphics.drawLine(). I have a custom picture of the figure in a .gif file, which I load as a BufferedImage object.

However, I want the player to see only part of the labyrinth at a time, and the screen should follow the figure in the game, as the player moves around. I'm planning to do this by creating an Image object of the whole labyrinth when it is created, and then "cutting" a square around the current position of the figure and displaying this with Graphics.drawImage(). I'm new with Swing though, and I can't figure out how to draw the figure at different positions "above" the labyrinth without redrawing the whole thing. Which container/component should I use for the labyrinth and then for the figure to achieve this?


and I can't figure out how to draw the figure at different positions "above" the labyrinth without redrawing the whole thing.

Use a JLabel containing an icon. Then you just use label.setLocation() to move the image. Swing is smart enough to repaint the old area (where the image was) and then paint the image at its new location.

You should be able to do this with a single JPanel. Your custom painting of the panel will paint the maze. The the label which is added as a child component will be painted on top of the maze.

Check out the last entry of this posting which contains an interesting approach for building the maze and it also supports scrolling of the maze as the player moves.

I think that the glass pane is the component you are looking for: it's a sort of glass placed onto the frame. Everything you draw on it will cover what's behind.. so you can achieve easily the effect without caring about clipping the original image.. see here!

You might look at JLayeredPane, discussed in How to Use Layered Panes and in this question.

Need Your Help

How to programmatically update the selected resource for link-with-editor functionality?

eclipse-plugin eclipse-rcp

My Eclipse plugin provides an editor which contains a list of files (as result of a dependency search). When the user selects a file in the list, this file/resource should be highlighted in package/

Moving a subsite to become the main site sharepoint 2013

sharepoint sharepoint-2013

I have a client who is setting up a sharepoint file share and for some reason has setup the site as a subsite on the default central administration sire (port 6042) instead of on the site on port 8...