初始化一张图片

4

我正在尝试为我的乒乓球游戏制作顶部和底部的墙壁。我认为一切都正确,但它无法运行,因为显示“本地变量wall可能未初始化”。如何初始化图像?

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);
  }
}

感谢所有回答我的人,我明白了。我没有意识到我只需要将wall = null设置为空即可。


在声明中将其设置为null即可。 - OldProgrammer
3个回答

4

你的图片确实是由该语句初始化的

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

然而,编译器抱怨该语句可能会失败,因为它在try/catch块中。一个可能的方法是将Image变量设置为null来“满足”编译器:
Image wall = null;

2

您正确地初始化了Image。Java抱怨的原因是您将其放在try块中。尝试块不能保证运行,并且您没有在catch块中补偿代码可能失败的可能性,因此当您调用window.drawImage()时,您(更重要的是,Java)无法确定wall是否存在。一个可能的解决方法是(剪切导入,但有一些参考代码):

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

始终对类声明的变量进行初始化非常重要

Image wall = null;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接