Initialize image

I am trying to make the upper and lower walls for playing pong. I think that everything is correct with me, but it will not work, because it says: "The local variable wall may not have been initialized." How to initialize the 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 replied that they understood. I did not understand that I just needed to set wall = null.

+3
source share
3 answers

Your image is really initialized by the expression

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

However, the compiler complains because this statement may fail because it is in a try / catch block. A possible way to simply “satisfy” the compiler is to set the Image variable to null:

Image wall = null;
+4
source

. , Java , , try. , catch, (, , Java) sure, , window.drawImage(). ( , ):

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();
        wall = new BufferedWindow(getWidth(), getHeight(), <Correct Image Type>);
    }

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

It is important to always initialize a variable declared by a class

Image wall = null;

0
source

All Articles