Applet: A user controlled Image - Stuck!

I need to have the user control the image via WASD keys to move around the screen. I have gotten this to work with a paint generated “rect” but can’t seem to get it to work with a gif image. I am still a beginner and am not the best coder.

NOTE: I have the gif saved onto my desktop. Will that affect my code?

Here’s my code:

package maze;


import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;


public class Maze extends JApplet implements KeyListener
{
   int x;
   int y;

   public void init()
   {
       
       
      setBackground(Color.black);
      x = 20;
      y = 20;
      addKeyListener(this);    
      
       Image img;
       img = getImage(getCodeBase(), "soldier.gif");
       setVisible(true);
   }

   public void keyPressed(KeyEvent e) {}
  
   public void keyReleased(KeyEvent e) {}
   
   public void keyTyped(KeyEvent e)
   {
      char c = e.getKeyChar();
      
      if (c == 'w')
      {
      	y -= 20;
      }
      else if (c == 's')
      {
      	y += 20;
      }
      else if (c == 'a')
      {
      	x -= 20;
      }
      else if (c == 'd')
      {
      	x += 20;
      }
      
      if (c != KeyEvent.CHAR_UNDEFINED)
      {
         repaint();
         e.consume();
      }
   }

   public void paint(Graphics g) 
   {
   	  requestFocus();	 // applet's initial focus

         g.drawImage(img,50,50, this); 
          
   	  if (!collisionDetection())
   	  {
	      g.setColor(Color.gray);
	      g.drawLine(0, 100, 250, 100);

	     
             
	  }
	  else
	  {
	  	  g.setColor(Color.yellow);
	  	  g.drawString("LOSER", 130, 150);
	  }
   }
   
   public boolean collisionDetection()
   {
   	  if (x < 250 && y < 100 && y + 20 > 100)		// line segment 1
      {
      	return true;
      }
      
      
      return false;
   }

public class DisplayImage extends JApplet 
{
	private Image img;

	public void init() 
	{
		 img = getImage(getDocumentBase(),"soldier.gif");
	}

	public void paint(Graphics g) 
	{
		 g.drawImage(img, 50, 50, this);
	}
}
}
   

The g.drawImage(img,50,50, this); above the collision if statement is giving me an error for “img”… Saying “Cannot find symbol” - “Symbol: variable img”. Not sure what is the problem. Help much appreciated. Thanks!

As soon as init() method is finished, the image is “lost”. This is because The image defined and initalised within init() method scope.

I believe you want to increase the scope of the img variable. To do this you would move the img declaration outside of the init() method. Which in this case would be the same level of the x and y variable declarations.