0

現在のプロジェクトを Eclipse で実行すると、エラーは発生しません。ただし、実行可能な jar にエクスポートした後は、まったく機能しません。コマンド プロンプトから実行すると、次のエラー メッセージが表示されます。

Uncaught error fetching image:
java.lang.NullPointerException
    at sun.awt.image.URLImageSource.getConnection(Unknown Source)
    at sun.awt.image.URLImageSource.getDecoder(Unknown Source)
    at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
    at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
    at sun.awt.image.ImageFetcher.run(Unknown Source)

テストの結果、プロジェクトに必要な画像を読み込もうとすると、次のような行でエラーが発生するという結論に達しました。

grassTile1 = rl.getImage("\\grassTile1.png");

rl は ResourceLoader のインスタンスであり、その getImage は次のとおりです。

public Image getImage(String x){
    URL y = this.getClass().getResource(x);
    System.out.println(y);
    Image img = tk.getImage(y);
    if(img==null) throw new IllegalArgumentException("Image at "+x+" not found.");
    System.out.println(y);
    return new ImageIcon(img).getImage();
}

tk は Toolkit.getDefaultToolkit(); を介して取得されます。イメージは、jar 内の ResourceLoader.class と同じディレクトリに存在します。ResourceLoader に存在する唯一の呼び出しを含む loadImages() への呼び出しをコメント アウトすると、プログラムが実行されますが、明らかに画像リソースはありません。

プログラムは Eclipse 内で期待どおりに実行されます。jar にコンパイルされたときに適切に機能するように、参照される相対パスにどのような変更を加える必要がありますか?

編集: フィードバックに基づく ResourceLoader.getImage() への変更。

public Image getImage(String x){
    URL y = this.getClass().getResource(x);
    System.out.println(y);
    ImageIcon icon = new ImageIcon(getClass().getResource(x));
    Image i = icon.getImage();
    return i;
}

これは、私が書いた元の getImage() 関数よりも良いですか、悪いですか?

更新 2: getImage() に渡されたデータから先頭のスラッシュを削除すると、Perception が示唆するように問題が修正されました。

4

0 に答える 0