Volken
Volken

Reputation: 255

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();
}

Upvotes: 0

Views: 123

Answers (4)

Spooler
Spooler

Reputation: 232

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"

Upvotes: 1

Binkan Salaryman
Binkan Salaryman

Reputation: 3058

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.

Upvotes: 0

Entara
Entara

Reputation: 1360

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")

Upvotes: 0

LeFex
LeFex

Reputation: 258

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".

Upvotes: 2

Related Questions