Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an Image

I'm trying to make top and bottom walls for my Pong game. I think I have everything right but it will not run because it says "The local variable wall may not have been initialized". How do I initialize an Image?

import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Wall extends Block
{
/**
 * Constructs a Wall with position and dimensions
 * @param x the x position
 * @param y the y position
 * @param wdt the width
 * @param hgt the height
 */
public Wall(int x, int y, int wdt, int hgt)
    {super(x, y, wdt, hgt);}

/**
  * Draws the wall
  * @param window the graphics object
  */
 public void draw(Graphics window)
 {
    Image wall;

    try 
        {wall = ImageIO.read(new File("C:/eclipse/projects/Pong/wall.png"));}
    catch (IOException e)
        {e.printStackTrace();}

    window.drawImage(wall, getX(), getY(), getWidth(), getHeight(), null);
  }
}

Thanks to everyone who answered I've figured it out. I didn't realize I just needed to set wall = null.

like image 572
LazerWing Avatar asked Mar 20 '23 14:03

LazerWing


1 Answers

Your image is indeed initialised with the statement

wall = ImageIO.read(new File("C:/eclipse/projects/Pong/wall.png"));

However, the compiler is complaining because that statement could possibly fail, as it is in a try/catch block. A possible way to just "satisfy" the compiler is to set the Image variable to null:

Image wall = null;
like image 132
Kent Shikama Avatar answered Mar 29 '23 17:03

Kent Shikama