2017-10-03 3 views
-1

イメージパスを含む文字列をこのオブジェクトイメージとして設定できるクラスを作成しようとしています。私は手動でこれをやったことがあります。つまり、メインクラスを拡張して新しいクラスを作成しますが、これはすぐに手を抜くことになります。私は子供のクラスを持っていたとき画像ファイルのパスを引数に指定してクラスを作成する際の問題

import java.awt.Image; 
import java.net.URL; 
import javax.swing.ImageIcon; 

public class Sprite { 
private int x; 
    private int y; 
    private ImageIcon ia; 
    private URL loc; 
    private Image image; 

public Sprite(int x, int y) { 
    this.x = x; 
    this.y = y; 
} 

public Sprite(int x, int y, String imgLoc) { 
    this.x = x; 
    this.y = y; 

    URL loc = this.getClass().getResource(imgLoc); //problem area is here 
    ia = new ImageIcon(loc); //and here 
    image = ia.getImage(); 
    this.setImage(image); 
} 

が、それはclassIはこのようなものに入れ子で働いていた:

public class Dude extends Sprite { 
    public Dude (intx, int y) { 
     super(x, y); 

     URL loc = this.getClass().getResource("images/dude.png"); 
     ia = new ImageIcon(loc); 
     image = ia.getImage(); 
     this.setImage(image); 
    } 
} 

しかし、私は2番目を使用しようとすると、ここで私は今のところしているコードがありますスプライトコンストラクタ、それは私に与えた

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
    at javax.swing.ImageIcon.<init>(ImageIcon.java:217) 
    at Sprite.<init>(Sprite.java:26) 

これを修正する方法の任意の提案?

+0

質問は? – lexicore

+0

おっと、私が遭遇したエラーを含めるのを忘れてしまった。今すぐ修正する必要があります。 – OneSurvivor

+1

あなたのリソースは存在しません。 – lexicore

答えて

0

私は解決策を見つけました。私はこれから学ぶための授業がすべて正しく呼ばれる絶対的に確認することだと思い

//Image is called: "images/dude2.png" 
//But I called it: "images/dude.png" 

:それはの線に沿って、私は少しイメージパスが間違って持っていたことが判明します。

+1

'NullPointerException'も' null'をチェックすることで回避できます。 https://stackoverflow.com/a/15581779/3196753も参照してください。 – tresf

関連する問題