【问题标题】:Initialize an Image初始化图像
【发布时间】:2014-02-15 02:55:30
【问题描述】:

我正在尝试为我的 Pong 游戏制作顶墙和底墙。我认为我一切正常,但它不会运行,因为它说“局部变量墙可能尚未初始化”。如何初始化图像?

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。

标签: java image initialization


【解决方案1】:

您正在正确初始化图像。 Java 抱怨的原因是你把它放在try 块中。 Try 块不能保证运行,并且您不能补偿代码在 catch 块中失败的可能性,因此您(更重要的是 Java)不能确定该墙会调用 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);
  }
}

【讨论】:

    【解决方案2】:

    始终初始化声明为类的变量很重要

    图像墙 = null;

    【讨论】:

      【解决方案3】:

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

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

      但是,编译器正在抱怨,因为该语句可能会失败,因为它位于 try/catch 块中。仅“满足”编译器的一种可能方法是将 Image 变量设置为 null:

      Image wall = null;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 2019-01-18
        • 2019-09-24
        • 1970-01-01
        相关资源
        最近更新 更多