Carpo23
Carpo23

Reputation: 25

Setting a background image in a simple java game

I'm making my first simple game, that looks like Space Invaders.

I have used paint for drawing my hero on my JPanel. Now I guess if it's possible, in a simple way, to add a background image on my JPanel.

ImageIcon img = new ImageIcon(this.getClass().getResource("back.gif"));
Image image = img.getImage();
setDoubleBuffered(true);    
hero = new Hero("hbarrel.gif",350,500); 

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(hero.getImage(), hero.getX(), hero.getY(), this);
    g2d.drawImage(image,0,0,this);
    // Toolkit.getDefaultToolkit().sync();
    g.dispose();
}

So, this is it: I tried to use my background img as hero img, and it works! but when I use the code above it only paints my hero img.... so it isn't a resource position issue.

Upvotes: 0

Views: 2315

Answers (2)

PeGiannOS
PeGiannOS

Reputation: 247

Well, try to paint the background image first and then the hero so that you have hero above background image

Upvotes: 0

Hakan Serce
Hakan Serce

Reputation: 11256

Override paintComponent(Graphics) method and use Graphics.drawImage() to do that in your own custom component.

Upvotes: 2

Related Questions