Search code examples
javauser-interfacedirectorysrc

Add picture to Java GUI at specific path


I need to add 3 pictures to my code . At the moment those 3 pictures are not at the SRC folder , but outside of it - I'm talking about Eclipse Project .

Here is my code :

Image myImage = new Image(null, "treasure1.jpg");

while (iterator.hasNext())
{

    String current = iterator.next();   // get an original room in the maze
    Coordinate mazeDot = null;
    if (this.m_rooms.containsKey(current))   // if the string key exists 
        {
            mazeDot = this.m_rooms.get(current);  // get the coordinate of that specific room as two Ints
            e.gc.drawImage(myImage,mazeDot.getXCoordinate(),mazeDot.getYCoordinate());
        }                   
}

But I want to put that picture ( treasure1.jpg ) in the src folder of my project . I've tried this code :

Image myImage = new Image(null, "src/treasure1.jpg");

but it didn't work , but compiled (after I put the picture in the src folder). The src is in lower case .

Any ideas what's wrong ?

Regards, Ron


Solution

  • If I understand correctly, you image is now part of your packages hierarchy. So you should be able to access it using the following snippet:

    Toolkit.getDefaultToolkit().getImage(getClass().getResource(path))
    

    where path is either a relative path to your image from the package in which your class is located, or the complete path starting at the root package, i.e:

    Relative: ressources/images/treasure1.jpg
    Absolute: /org/you/ressources/images/treasure1.jpg
    

    Or, if your image is in the same package as your class, just use the name of the image. You can also use ImageIO instead of Toolkit as far as I know.