Question

I need to layer JPanels but I don't know how. I have 3 panels, the first is for the background, the second is for a Character/Sprite to move around and layers the first panel(background, and the third is a bar off to the side (Used for buttons and has nothing to do with they layers). How do I layer panel 1 and panel 2?

edit: The background is made up of a grid of 25x25 labels with an icon in each.

Was it helpful?

Solution

Some options:

  • Use a JLayeredPane which can layer components using a z-order Integer constant. Remember that when doing this, you are also essentially using a null layout, and so you will be fully responsible for setting the size and position of all components added to the JLayeredPane.
  • If all the background is doing is painting an image, you could use a single JPanel, and then simply paint the image as a BufferedImage that is displayed in the JPanel's paintComponent method. The sprite would also be painted but its location would vary.

OTHER TIPS

See How to Use Layered Panes.

Don't forget to use:

panel.setOpaque(false);

Or you don't need to layer panels. You can just paint a background image on the panel. See Background Panel for an example of this.

We just recently worked on a top-down video game for my CSC class. All we did was draw the background and then all the sprites after it in the paint() method on the JPanel. We also used a Timer and an ActionListener to constantly update the JPanel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top