2014-02-15 56 views
3

我正在嘗試爲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。

+0

只是在聲明中將其設置爲null。 – OldProgrammer

回答

3

您的圖片確實與聲明

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

然而,編譯器抱怨,因爲語句可能失敗的可能,因爲它是在一個try/catch塊初始化。一種可能的方法只是「滿足」的編譯器是將圖像變量設置爲空值:

Image wall = null; 
0
聲明類的變量的

總是初始化是重要

圖片壁= NULL;

1

您正在初始化圖像正確。 Java抱怨的原因是你有一個try塊。嘗試塊不能保證運行,並且你不補償在catch塊中代碼失敗的可能性,所以你(更重要的是,Java)不能在你調用窗口的時候存在這個牆將存在的確定 .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); 
    } 
}