1

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.

Andrew Thompson
169k42 gold badges224 silver badges441 bronze badges
asked May 19, 2013 at 4:45

3 Answers 3

2

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.
answered May 19, 2013 at 4:48
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered May 19, 2013 at 4:47

Comments

1

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.

answered May 19, 2013 at 5:35

1 Comment

I agree with this other than the drawing in the JPanel's paint(...) method. This method is responsible for painting the component, its borders, and its children, and if you don't want to risk messing up with faulty painting of the latter two considerations (the border and the children), it is usually much better to do your painting in a JPanel's paintComponent(Graphics g) method.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.