How to use JLayered Pane to display an image on top of another image?

We are working on a pacman game and we want to add a pacman photo on top of the background. If someone could provide sample Jlayered Pane implementation code that would be great.

Here are some of the code we tried to write. When we try to start it, nothing is displayed:

  JLayeredPane pacman = new JLayeredPane();  

  pacman.setPreferredSize(new Dimension(576, 655));





  ImageIcon sprite = new ImageIcon("C:\\\\Users\\\\16ayoubc\\\\Desktop\\\\Pacman-moving.gif");  
  ImageIcon background = new ImageIcon("C:\\\\Users\\\\16ayoubc\\\\Desktop\\\\background.png");  

  JLabel pacmansprite = new JLabel(sprite);
  JLabel background1 = new JLabel(background);

  background1.setVisible(true);
  pacman.setLocation(255, 255);
  pacman.setVisible(true);
  pacman.setOpaque(true);

  pacman.add(background1, new Integer(0));
0
source share
1 answer

I think you just need to add the canvas to JLayeredPane, and then draw the image with java2D(found in java.awt.Graphicsand java.awt.Graphics2D. More information on this is available.). than try using the method Graphics2D drawImage(BufferedImage img, int x, int y, int width, int hight);. It may be difficult, but may work better.

, !

0

All Articles