私が作成したJListにアイコンを表示する際に問題が発生しています。関数getResource()にパスを渡して、URLオブジェクトにリソースを格納しています。しかし、getResource()関数を呼び出すたびに、ディレクトリにイメージが存在していてもnullが返されます。getResource()を使用してJListのアイコンを取得および表示する
私はstackoverflowと他のサイトで見てみましたが、私はこの問題の解決策を見つけることができません。私は自分のプロジェクトディレクトリ内の複数の場所に画像を保存しようとしても役に立たなかった。役立つなら、私はEclipse IDEを使用しています。だから、私は/ src /、/ src/resources /、およびプロジェクトフォルダにファイルを保存しました。ここで
は私のコードです:
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.*;
@SuppressWarnings("serial")
public class JListRenderer extends DefaultListCellRenderer
{
private static ArrayList<CakeRecipe> cRecipes;
private ImageIcon[] images;
// Index of cake recipe
private int cakeIndex;
JListRenderer(ArrayList<CakeRecipe> recipes)
{
cRecipes = recipes;
// Initializes an array of ImageIcons FileHander.jpgCounter() counts the amount of JPG's in the folder, FileHandler.getPath() gives you the filepath
images = new ImageIcon[FileHandler.jpgCounter(new File(FileHandler.getPath()))];
for(int i = 0, j = images.length; i < j; i++)
images[i] = createImageIcon("/resources/" + cRecipes.get(cakeIndex).getPhoto()); // cRecipes.get().getPhoto() gives you the filename of the village only (e.g.: photo.jpg)
}
protected static ImageIcon createImageIcon(String path)
{
URL imgURL = JListRenderer.class.getResource(path);
if(imgURL != null)
return new ImageIcon(imgURL);
else
{
System.err.println("Could not find image. Certain menu elements may not display properly");
return null;
}
}
...
このコードの動作は、万一または私が正しくURLまたはのgetResource()を使用していないのですか?画像はディレクトリにあり、画像のパスと同じパスを渡しています。例:
"/resources/photo.jpg"
ご協力いただければ幸いです。ありがとうございました。
編集:この問題はEclipseで発生しました。ビルドパスにリソースを登録しませんでした。シンプルな「リフレッシュ」で問題は解決しました。皆様のご協力ありがとうございます。
「photo.JPG」ではなく「photo.jpg」であることは確かですか?正しいケースは、Jarsの 'getResource()'にとって不可欠です。 –
ところで - 画像は瓶の中に入っていますか? –
ファイルはphoto.jpgでしたが、Eclipseに問題がありました。助けてくれてありがとう。 – Drake