[英]Nullpointer exception when drawing ImageIcons
我正在嘗試為非常簡單的2D游戲創建圖形。 我有imageIcons的arrayLists,當玩家移動時會連續繪制它們。 一個代表向上,一個代表向下,依此類推。截至目前,我還沒有完成的精靈,所以我用臨時圖像替換了每個單獨的精靈。
//this is inside the constructor
playerUp.add(new ImageIcon("Player1.png"); //will be a different image, but this image still exists
playerUp.add(new ImageIcon("Player1.png"); //will be a different image, but this image still exists
playerUp.add(new ImageIcon("PLayer1.png"); //will be a different image, but this image still exists
然后,將它們繪制到屏幕外的圖像,然后將其繪制到屏幕上以防止閃爍。
//offg is the graphics object of the offscreen image and g is for the panel
offg.clearRect(0, 0, panel.getWidth(), panel.getHeight());
playerUp.get(0).paintIcon(panel, offg, x, y);
g.drawImage(offscreen, 0, 0, panel); //this is where the error occurs!
無論如何,我嘗試使用的代碼中存在某種錯誤:
playerUp.add(new ImageIcon(getClass().getResource("Player1.png")));
但是我不知道我是否需要或如何正確使用它(在研究時,我經常看到它),但這並不能解決問題。 另外,我確保圖像與.class和.java文件位於同一文件夾中。
另外,我創建了一個單獨的類,將一個ImageIcon直接繪制到面板上,並且使用了完全不同的圖像。
ImageIcon ii = new ImageIcon("downlaodedimage.png"); //downlaodedimage.png is the different image
ii.paintIcon(panel, g, 0, 0);
這給出了一個空指針異常。 我用了:
System.out.println(ii);
並且它打印出了downloadedimage.png,所以我不知道問題出在哪里?
問題是該行上的某些內容尚未初始化。 嘗試調試它以查找哪個為空,並確保在調用之前對其進行了初始化。 或者,如果這是在游戲循環中發生的,並且變量在循環中稍后被初始化,則可以用try-catch包圍它,直到變量被初始化為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.