Help with Buffered Images

Hi,

I have to make a space invaders game and am having some problems with using images for my gaming entities. I have a GameEntites class that will be extended by AlienEntity, shot and ship. I have a class called ImageHandler that will be used to represent the entites with images. I’ve never used BufferImage’s before and can’t get it running.

My ImageHandler class is as follows:


import java.awt.image.BufferedImage;
import java.io.PrintStream;
import java.util.HashMap;
import javax.imageio.ImageIO;

public class ImageHandler
{    
    private HashMap images;
    
    
    public ImageHandler()
    {
        images = new HashMap();
    }

    public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);
            return ImageIO.read(url);
        }
        catch(Exception e)
        {
            System.exit(0);
            return null;
        }
    }

    public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
        
        return image;
    }

    public HashMap getImages()
    {
        return images;
    }

    public void setImages(HashMap val)
    {
        images = val;
    }

}

and my GameEntites class that will use the ImageHandler is as follows:

package InvadersGame;

import java.awt.Graphics;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;



public abstract class GameEntities {
    
    private double x, y;
    private int width, height;
    private String imageName;
    private boolean deletionMark = false;
    private SpaceInvaders invaders;
    private BufferedImage image;
    
    
    public GameEntities(SpaceInvaders invaders) 
    {
        this.invaders = invaders;
        
    }    
       
    public double getX()
    {
        return x;
    }
    
    public double getY()
    {
        return y;
    }
    
    public int getWidth()
    {
        return width;
    }
    
    public int getHeight()
    {
        return height;
    }
    
    public Rectangle getBounds()
    {
        return new Rectangle((int)x, (int)y, width, height);
    }
    
    public void setX(int x)
    {
        this.x = x;
    }
    
    public void setY(int y)
    {
        this.y = y;
    }
    
    public void setWidth(int width)
    {
        this.width = width;
    }
    
    public void setHeight(int height)
    {
        this.height = height;
    }
    
    public boolean deletionMarked()
    {
        return deletionMark;
    }
    
    public void setDeletionMarkedTrue(boolean value)
    {
        deletionMark = value;
    }
    
   public String getImageName()
    {
        return imageName;
    }

    public void setImageName(String name)
    {
        imageName = name;
        image = ImageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }
        
    public boolean collidesWith(GameEntities other) 
    {        
        Rectangle thisEntity = new Rectangle();
        Rectangle otherEntity = new Rectangle();        
        
        thisEntity.setBounds((int)this.getX(), (int)this.getY(), this.getWidth(), this.getHeight());
        otherEntity.setBounds((int)other.getX(),(int)other.getY(), other.getWidth(), other.getHeight());
        
        return thisEntity.intersects(otherEntity);
    }
    
    public abstract void move();
    
    public abstract void paint(Graphics g);   
    
}

The ImageHandler class compiles fine but when I compile the GameEntites class the setImageName method causes an error and I get the following error:

Compiling 1 source file to C:\Documents and Settings\Nick\SpaceInvaders\build\classes
C:\Documents and Settings\Nick\SpaceInvaders\src\InvadersGame\GameEntities.java:89: cannot access InvadersGame.ImageHandler
bad class file: C:\Documents and Settings\Nick\SpaceInvaders\src\InvadersGame\ImageHandler.java
file does not contain class InvadersGame.ImageHandler
Please remove or make sure it appears in the correct subdirectory of the classpath.
        image = ImageHandler.getImage(imageName);
1 error
BUILD FAILED (total time: 2 seconds)

Can someone PLEASE explain what’s going wrong and how I can sort the problem.

Any help would really be appreciated,

Cheers :wink:

Don’t worry, I’ve sorted the problem now :).

how about sharing with us then? Somebody might need it.

The problem was with this method:

public void setImageName(String name)
    {
        imageName = name;
        image = ImageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }

for some reason I put image = ImageHandler.getImage(imageName) when I should have created a new instance of ImageHander (my java lingo isn’t too good, but I think that’s the correct terminology). So it should have been something like:

public class GameEntities {
    
    ........
    private ImageHandler imageHandler;

    ........
    .......

    public void setImageName(String name)
    {
        imageName = name;
        image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }

I’ve now sorted that out and am having some other difficulties with the ImageHandler and Buffered images. I’m trying to sort it now but may need some help if I can’t get it working.

:slight_smile:

I can’t get my ImageHandler class working and need some help.

First of all, here are my 4 classes:

package InvadersGame;

import java.awt.image.BufferedImage;
import java.io.PrintStream;
import java.util.HashMap;
import javax.imageio.ImageIO;

public class ImageHandler
{    
    private HashMap images;
    
    
    public ImageHandler()
    {
        images = new HashMap();
    }

    public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);
            System.out.println(url); //to check whether the image was found
            return ImageIO.read(url);            
        }
        catch(Exception e)
        {
            System.exit(0);
            System.out.println("image not found");
            return null;
        }
    }     
    
     public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
        if(image == null)
        {
            System.out.println("image null");          
        }
        else System.out.println("not null");
        
        return image;
    }
     
     
    public HashMap getImages()
    {
        return images;
    }

    public void setImages(HashMap val)
    {
        images = val;
    }

}

and…

package InvadersGame;

import java.awt.Graphics;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;

public class GameEntities {
    
    protected double x, y;
    protected int width, height;
    protected String imageName;
    protected boolean deletionMark = false;
    protected SpaceInvaders invaders;
    protected ImageHandler imageHandler;
            
    
    
    public GameEntities(SpaceInvaders invaders) 
    {
        this.invaders = invaders;
        imageHandler = invaders.getImageHandler();
        
    }    

    public void setX(int x)
    {
        this.x = x;
    }
    
    public void setY(int y)
    {
        this.y = y;
    }
   
   public String getImageName()
    {
        return imageName;
    }

    public void setImageName(String name)
    {
        imageName = name;
        BufferedImage image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
         
    }
    
    public SpaceInvaders getGame()
    {
        return invaders;
    }
        
    public boolean collidesWith(GameEntities other) 
    {        
        Rectangle thisEntity = new Rectangle();
        Rectangle otherEntity = new Rectangle();        
        
        thisEntity.setBounds((int)this.getX(), (int)this.getY(), this.getWidth(), this.getHeight());
        otherEntity.setBounds((int)other.getX(),(int)other.getY(), other.getWidth(), other.getHeight());
        
        return thisEntity.intersects(otherEntity);
    }
    
    public void move(){}
    
    public void paint(Graphics2D g)
    {
         g.drawImage(imageHandler.getImage(imageName), (int)x, (int)y, invaders);
    }
    
}

and…


package InvadersGame;

import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.lang.Math;
import java.util.Random;



public class AlienEntity extends GameEntities {
    
    //double x, y;
    int alienType;
    int speedx = 2;
    int speedy = 2;
    int firingFrequency;
    
   
    
    public AlienEntity(SpaceInvaders invaders)
    {
        super(invaders);  
        //setImageName("alien4.gif");
    }   
        
    public void move()
    { 
        y = y + speedy;   
       
    }
    
    public void paint(Graphics2D g)
    {
        
        this.setImageName("alien4.gif");        
    }
              
    
}

and finally…



package InvadersGame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.image.BufferStrategy;


public class SpaceInvaders extends Canvas{
    
    JPanel panel;
    //AlienEntity al, al2;
    Graphics2D g2;
    boolean gameRunning = true;
    ArrayList<GameEntities> entitiesList;
    AnimationThread thread;
    private BufferStrategy buffer;
    ImageHandler imageHandler;
    
    class AnimationThread extends Thread
    {
        public void run()
        {
            while(true)
            {
                paintAlien();
                moveAlien();
                try
                {
                    sleep(50);
                }
                catch(InterruptedException e){}
            }
        }
    }
    
    public SpaceInvaders() 
    {
        super();
        
        imageHandler = new ImageHandler();
                
        JFrame window = new JFrame("Space Invaders");
        JPanel panel = (JPanel)window.getContentPane();
        setBounds(0, 0, 800, 600);
        
        panel.add(this);
        window.setBounds(0, 0, 800, 600);
        window.setVisible(true);          
        
        window.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
               
        setFocusable(true);
        
        this.createBufferStrategy(2);
        buffer = getBufferStrategy();
        
        thread = new AnimationThread();   
    
        initialise();
    }
    
    public void initialise()
    {
        entitiesList = new ArrayList();
        for(int i=0; i<10; i++)
        {
            AlienEntity alien = new AlienEntity(this);
            alien.setX(60*i);
            
            entitiesList.add(alien);
        }
    }
        
    public void paintAlien()
    {
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
        
                        
        for(int i=0; i<10; i++)
        {
            entitiesList.get(i).paint(g);
        }
        
        buffer.show();
    }
    
    public void moveAlien()
    {
         for(int i=0; i<10; i++)
        {
            entitiesList.get(i).move();
            System.out.println(entitiesList.get(i).getY());
        }
    }
    
    
    public void setBufferstrategy(BufferStrategy buffer)
    {
        buffer = buffer;
    }
    
    public ImageHandler getImageHandler()
    {
        return imageHandler;
    }

    public static void main(String[] args)
    {        
        SpaceInvaders canvas = new SpaceInvaders();   
        canvas.thread.start();
    }
    
}

What happens is in the AlienEntity paint() method I set the image name as alien4.gif:

public void paint(Graphics2D g)
    {                
        this.setImageName("alien4.gif");        
    }

which calls the setImageName() method in the GameEntities class:

public void setImageName(String name)
    {
        imageName = name;
        BufferedImage image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();         
    }
    

What this does is call the getImage(String name) method in the image handler class which should load the appropriate image:

public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
        if(image == null)
        {
            System.out.println("image null");          
        }
        else System.out.println("not null");
        
        return image;
    }

I’ve tried running the spaceInvaders class and get a null pointer exception. I put a print line in the image loader method (in ImageHandler) which says that url = null:


public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);

            System.out.println(url); //to check whether the image was found......returns null

            return ImageIO.read(url);            
        }
        catch(Exception e)
        {
            System.exit(0);
            System.out.println("image not found");
            return null;
        }    
    }

I assume the whole problem lies in the fact that it’s not finding my image and so can’t load it. I’ve put the image in the same folder and from within netbeans set the working directory to this folder in a hope that it would find and load the image.

Can someone PLEASE check my code to see if there’s any fundamental problem and let me know how to fix this bug.

Cheers :slight_smile:

if url is null then you know what’s wrong… that line. You need to track why is it null. Print out your name before calling ImageIO.read() to see if name is correct. If it is then either you don’t have the image in right folder either you don’t have enough privilages to read the file (image).
If it still dosen’t work write a simple test class and only put ImageIO.read(“alien4.gif”) into it and check if you still get null.

btw. I have:

url = Viktorije.class.getClassLoader().getResource(path);

…try it.

Don’t know how Netbeans starts programs… try manually with console and make sure your image has exactly the same name.