问题
I've seen many different examples showing how to set a JFrame's IconImage
so that the application uses that icon instead of the standard coffee mug. None of them are working for me.
Here's "my" code (heavily borrowed from other posts and the internet at large):
public class MyApp extends JFrame
{
public MyApp()
{
ImageIcon myAppImage = loadIcon("myimage.jpg");
if(myAppImage != null)
setIconImage(myAppImage.getImage());
}
private ImageIcon loadIcon(String strPath)
{
URL imgURL = getResource(strPath);
if(imgURL != null)
return new ImageIcon(imgURL);
else
return null;
}
}
This code fails down in loadIcon
when making a call to the getResource()
method. To me, there's only 2 possibilities here: (1) the myImage.jpg
is in the wrong directory, or (2) getResource()
doesn't like something about my image (I had to convert it from CMYK to RGB in Photoshop so I could use the same image elsewhere with ImageIO
.)
I have used the System.out.println(new File(".").getAbsolutePath());
trick to locate the directory where the image JPG should be stored, and still nothing worked. I have subsequently placed the JPG in just about every directory inside my project, just to rule file location out as the culprit.
So that leaves me to believe there's something that getResource()
doesn't like about the JPG itself. But I have now already exhausted my understanding of images and icons in the mighty, wide world of Swing.
My JPG loads fine in other image viewers, so that's ruled out as well. Anyone have any ideas?
Thanks in advance!
回答1:
put the image in the root of the classpath and say getResource("classpath:myimage.jpg");
The problem with your code is that jvm is unsure where to lookup the image file so its returning null.
Here is a nice link about classpath
回答2:
It should be
if(imgURL != null)
^
instead of
if(imgURL !- null)
and
URL imgURL = this.getClass().getResource(strPath);
instead of
URL imgURL = getResource(strPath);
Then it works fine, if "myimage.jpg"
is in the same dir with MyApp.class
回答3:
I have tried following which was a answer for same kind of question like yours. And it works for me.
Try putting your images in a separate folder outside of your src folder. Then, use ImageIO to load your images. (answered Aug 27 '13 at 0:18 AndyTechGuy)
frame.setIconImage(ImageIO.read(new File("res/icon.png")));
回答4:
Two suggestions:
- Try using the
getClass().getResource("x.jpg")
, and putting the file directly in the same folder as the.class
file of the class you are in. - Make sure the name is identical in case - some operating systems are case sensitive, and within a JAR, everything is case sensitive.
来源:https://stackoverflow.com/questions/7194734/how-to-set-icon-image-for-swing-application