I am following the Snake Java games tutorial and always get this error:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
ball = iid.getImage();
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at snake2.Board.<init>(Board.java:52)
at snake2.Snake.<init>(Snake.java:10)
at snake2.Snake.main(Snake.java:22)
I actually just copied and pasted the code to see how it works. They are in the right packages too; but when I try to run it, I always end up with this error.
The image should be in the same package (folder in OS terms) as the compiled class. Check whether you have both .class and .png in the same folder. If not, you can use classpath-relative paths in getResource(..), by starting with /
Try this:
ImageIcon iid = new ImageIcon(this.getClass()
.getClassLoader().getResource("ball.png"));
ball = iid.getImage();
Make sure image is in the same folder as java file.
Try using System.out.println(System.getProperty("java.class.path")); to find out location of your .class file and place the images in this folder.
It is general risky to load resources using relative paths, I'd always recommend using absolute paths, so do
/ball.png
if the the image is at the root of your classpath, or add a path to the location.
You have to put the image file(ball.png) into your classpath. More details, please take a look at the Javadoc.
if the resource is in your classpath then you should be trying "this.getClass().getClassLoader().getResource("ball.png")". For you actual code to work, the ball.png needs to be in the location where your .class file is (i.e., inside the package).
Go to project >clean in the eclipse it would refresh the package explorer and you won't face this problem anymore.
You may need to add the file to your build resources, something like this:
<build>
<resources>
<resource>
<directory>path\to\resources</directory>
<includes>
<include>ball.png</include>
</includes>
</resource>
</resources>
You can use only path of your image. I think this will help you:
Use this:
ImageIcon iid = new ImageIcon("C:\\Users\\ranig\\My\\spaceinvaders\\ball.png");
Note: C:\\Users\\ranig\\My\\spaceinvaders\\ball.png is the whole path of ball.png image.
instead of this:
ImageIcon iid = new ImageIcon(this.getClass().getResource("ball.png"));
Note: If u want to only try snake code and only want to get output.
I will make it simple for you . Here is an example:
Icon bug = new ImageIcon(getClass().getResource("bug1.png"));
here "bug1.png" is the resource and if it is unavailable then it can cause error as you have discussed here.
Import an image to the same directory in which your program resides.
You can also give whole path to it as well
ImageIcon(getClass().getResource("C://me/file/bug1.png"));
The resource so named wasn't found. It needs to be in the same directory as the .class file you are calling it from. See the Javadoc.
Related
After I've searched for a solution for my problem & reading similar questions which are very more professional than mine,... well, I hope you pay attention to my problem, even though it seems simple!
I'm working on a project which open files by FileChooser, then I'm trying to show it on a pane. The problem is getClass().getResourceAsStream(file.getAbsolutePath()) returns null.So while I can print the path & see it's true, but I cannot use it in creating images. Part of my code is:
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(stage);
...
Image img = new Image(getClass().getResourceAsStream(file.getAbsolutePath());
The exception is:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null ...
I work on Ubuntu by NetBeans.
I really appretiate helps. Thanks.
Use ImageIO:
Image img = ImageIO.read(file);
getResourceAsStream requires a path on the class path. As the resource could be in a jar, its full URI would be jar:file:/..../xyz.jar!/.... And File is on the file system.
One cannot mix those, only Path is a new generalisation allowing paths in several "file" systems.
I need to get a resource image file in a java project. What I'm doing is:
URL url = TestGameTable.class.getClass().
getClassLoader().getResource("unibo.lsb.res/dice.jpg");
The directory structure is the following:
unibo/
lsb/
res/
dice.jpg
test/
..../ /* other packages */
The fact is that I always get as the file doesn't exist. I have tried many different paths, but I couldn't solve the issue.
Any hint?
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
leading slash to denote the root of the classpath
slashes instead of dots in the path
you can call getResource() directly on the class.
Instead of explicitly writing the class name you could use
this.getClass().getResource("/unibo/lsb/res/dice.jpg");
if you are calling from static method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located
I want to load an image which is in my projet folder as : /src/images/URL.jpg
I tried this code :
BufferedImage image = ImageIO.read(getClass().getResource("/images/URL.jpg"));
But I'm getting this error :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Personel.PersonnelMainForm.print(PersonnelMainForm.java:464)
How can I solve this problem ?
From personal experience I use:
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/images/image.jpg"));
I get the resource as a stream and that seems to work fine for me.
You can try this version of read, which takes File as an argument.
BufferedImage image = ImageIO.read(new File("path"));
where path is the path to you file, absolute or relative as you need.
Another option, if you really want to load it as a resource, would be editing your classpath, as per this question.
I suppose you have a java class in the package.
You have to move up so many times as package levels.
Example:
Java class is defined as org.test.MyClass
you have to go up twice (../../) to be in the main directory.
I've made an audio player and the jar was made with netbeans. To load the images I've used:
ClassLoader cl = this.getClass().getClassLoader();
URL playerIconURL = cl.getResource("tp/audioplayer/Images/icon.png");
if (playerIconURL != null){
ImageIcon playerIcon = new ImageIcon(playerIconURL);
frame.setIconImage(playerIcon.getImage());
}
else{
System.err.println("cannot load player icon");
}
I mention that the folder Images is in the src/tp/audioplayer.
When I'm running the application inside netbeans everything is allright, but when I execute the jar in command prompt,the application starts but it's blank and it blocks and I get:
Can you tell me what I've done wrong or what is the problem? Thanks in advance!
If tp is in your classpath you will have to load it with cl.getResource("/tp/audioplayer/Images/icon.png") if tp is NOT a source folder (but still added to the buildpath.
If you add tp as a sourcefolder then
cl.getResource("/audioplayer/Images/icon.png")
Note that jars are casesensitive, make sure you the case-sensitive file-path.
Try any of these:
// using getResourceAsStream
InputStream is = this.getClass().getResourceAsStream( "picture.gif" );
// or
InputStream is = MyClass.class.getResourceAsStream( "stuff.ser" );
// or
InputStream is = MyApp.class.getClassLoader().getResourceAsStream( "InWords.properties" );
The resource in the jar file must be qualified with same package name as the class you call getResourceAsStream from. Alternatively, you can use an absolute name beginning with a / where dots get mapped to /s. If you don’t have a lead /, you have a relative name, and the name of the package will be prepended. If you use a /, you must include the name of the package yourself, or whatever name the resource is filed under in the jar.
For example you could specify /com/mindprod/mypackage/mystuff.ser or /com.mindprod.mypackage.mystuff.ser or simply mystuff.ser. Don’t use Windows style filenames with . These are not filenames, but Java resources that live along with the class files either in jars or sometimes freestanding on disk, or on the server.
In theory, getResourceAsStream will look in the local classpath, in the jar and in the directory where the class file was loaded from.
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!
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")));
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
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
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.
You can try to use a "/" before your filename.
getClass().getResource("/myimage.jpg")
If you look into your build-output folder (target) you can look for your class where you are trying to get your resource from.
Your resources will probably be copied in some folders above.
For example your target directory could look like this:
target
|- de.example.app
|- Main.class
|- Main-x.y.z.jar
|- myimage.jpg
So if you just go for getClass().getResource("myimage.jpg") it will look under the folder target/de/example/app and won't find a jpg there.
You need to tell him that you want to look under the root-folder (target/**). That's why you need to place a "/" before your file.