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

一笑奈何 提交于 2019-12-25 01:46:37

问题


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

Here is some of the code we attempted to write. When we try to run it, nothing displays:

  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));

回答1:


I think that you should just add a canvas to the JLayeredPane, and than paint the image using java2D (found in java.awt.Graphics, and java.awt.Graphics2D. More info on this is available.). than, try using the Graphics2D method drawImage(BufferedImage img, int x, int y, int width, int hight);. This may be complicated, but it might work better.

I hope this works!



来源:https://stackoverflow.com/questions/23246255/how-to-use-jlayered-pane-to-display-an-image-on-top-of-another-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!