views:

132

answers:

3

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?

+1  A: 

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

trashgod
+2  A: 

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!

Jack
+2  A: 

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.

camickr