简体   繁体   中英

Adding/Loading an image in java

I am trying to load an image to display on the screen (just to get an idea of how to do it).

The problem is that when the program tries to load "apple.png" (which is saved on my desktop), it cannot find the image - Where do image files need to be stored in order for them to be found? Here is my loading method:

private void loadImage() {
    ImageIcon appleIcon = new ImageIcon("apple.png");
    Image appleImage = appleIcon.getImage();
}

If you want to reach it from the desktop, you should use the complete path. The easiest way to handle resources would be to create a folder in you java project, which you can access via "folderName/fileName.example".

Using the full path is an option C:\\filefolder\\file.jpg

To answer your question though Wherever your java file is is where it's going to think "home is" make yourself a java workspace to put your java source files in and inside it create a folder to put any assets you want in that way you will simply be able to call "apple.jpg"

if you want use the file name only, the file path ("apple.png")is relative to the source folder. so you have to place it in there.

you could also use absolute the file path to your desktop (sthg like "C:\\Users\\your.name\\Desktop")

From the javadoc :

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify:

new ImageIcon("images/myImage.gif")

As @Shriram mentioned, when you only specify the filename (with extension), it will search for that file in the current directory.



Hint: There exists an constructor overload which takes an URL as argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM