簡體   English   中英

獲取圖像時發生NullPointerException

[英]NullPointerException while getting an Image

我在最新的游戲中無法設置圖像。 當我調用方法getImage(String) ,我像這樣得到Image:

Image head = getImage("Torso_model_01.png");

我收到以下錯誤消息:

Err: java.lang.NullPointerException
  At PB2Main.Body(Body.java : 27)
  ...

等等...

本教程中 ,它說明了如何使用ImageIcon來獲取圖像,如下所示:

String imgFile = "Images/" + img;
URL imgURL = getClass().getClassLoader().getResource(imgFile);
ImageIcon imageIcon;
Image image;
 if(imgURL != null){
  imageIcon = new imageIcon(imgURL);
  image = imageIcon.getImage();
 }

 final Image anImage = image;

我為此做了一個方法:

public URL getURL(String img){
  String imgFile = "Images/" + img;
  URL imgURL = getClass().getClassLoader().getResource(imgFile);
  return imgURL;
}

然后我做了一個叫做getImage(String)的方法

public Image getImage(String img) {
  ImageIcon imageIcon;
  Image image;
  URL imgURL = getClass().getClassLoader().getResource(getURL(img));
  if(imgURL != null){
   imageIcon = new ImageIcon(imgURL);
   image = imageIcon.getImage();
   return image;
  }
   System.err.println("Unable to Locate Image: " + imgURL);
}

現在,我有一個名為Body的課程。 在該類中,我有一個構造函數:

public Body(float x, float y, String head, String torso){//atm this is just so i can                    get the image to actually draw on the screen
Image Head = debugger.getImage(head);// debugger doubles as a library and debugger
//i also can't have this class extend debugger otherwise it will create a window :/
// is that a glitch or something in Java? :L perhaps i just don't understand
// inheritance very well and what happens exactly when you inherit a class :(
Image Torso = debugger.getImage(torso);

 g2.drawImage(Head, canvas.geWidth()/ 2,canvas.getHeight()/2, null)// canvas: the window to  
 //draw to
 // can someone also quickly explain in their answer what an image observer is please?
 g2.drawImage(Torso, Head.getX() - 5, Head.getY() - 5, null);
}

編譯器給我以下錯誤消息:

java.lang.NullPointerException
At PlazmaBurst2.Body(Body.java: 37)

//the code it brings me to is line 1 in the constructor:
/* null: */ Image Head = debugger.getImage(img);

我不明白此NullPointerException的來源。 我完全按照他們在同一站點的“自定義圖形編程”部分中操作來做的。

如果僅復制並粘貼代碼,則代碼工作正常,但如果使用方法getImage(String)則代碼無法正常工作。

您的問題是在getImage(String)第3行上:

URL imgURL = getClass().getClassLoader().getResource(getURL(img));

這應該更改為:

URL imgURL = getURL(img);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM