I am having trouble referencing a file in my home folder. The file contains an image that I am using as the ImageIcon for a button. Here's my code to build the button:
And here's the code where I reference the file:
I am getting a null pointer exception on the line with the filepath, which I take to mean that the filepath is incorrect for the image file.
The image file is in a folder called buttons, which is located in the main folder of my program (not the src folder, but the folder that contains the src folder).
I have looked and looked and looked, but I can't find anything definitive on the syntax to reference this filepath.
Can anyone help me out? Thanks in advance!
What you should do is package the images into your project / JAR and use them as a resource. Use Class#getResource() (or the related ClassLoader#getResource()) method to load it. Note, the images should be in your classpath, not a random part of your file system.
edit: I was thinking that maybe it had to do with the size of the image vs the size of the button? I'm not sur ethis is right either as a tutorial I read said that if that was the case, part of the image would still show up, and I'm getting nothing.
edit: I attached a screenshot of the button package I put into the src folder just to verify that I am referencing it correctly. The code that references it is this:
like I said, I'm not getting any runtime or compile time errors, so I'm hopeful that this part of the code is correct, but if not, please clue me in.
james falk wrote:I'm not sure that's the answer, just because when I run the program, it compiles fine and throws no errors, which means that the program can recognize where the images are and is simply not loading them onto the buttons (right?).
The compiler never cares about checking existence of files, so it compiles fine does not mean the image's path is correct!
james falk wrote:Is there some command which makes the images show up? Maybe something to do with validate(), or something similar?
There is no such complicate things for show up images on buttons. It's pretty simple if you do it right. As Steve Luke pointed out, you need to check your image's path. Surely you did something wrong with it.