Search code examples
javagnomegdk

Java GDK+: Pixbuf image not found


Relative to which directory is the file path argument of the org.gnome.gdk.Pixbuf constructor? And where should I place the file?

Main.java

public class Main
{
    public static void main( String... args )
    {
        Gtk.init( args );
        new Example();
        Gtk.main();
    }
}

Example.java

public class Example
{
    private Pixbuf icon;

    public Example()
    {
        try {
            icon = new Pixbuf( "images/bolt.png" );
        } catch ( FileNotFoundException e ) {
            e.printStackTrace();
        }
    }
}

It throws the following exception:

java.io.FileNotFoundException: images/web.png not found

My directory structure is:

enter image description here


Solution

  • Use this.getClass().getResourceAsStream(/images/bolt.png) to get an InputStream and use this answer to convert it to a byte[], which you can pass to the Pixbuf constructor.

    If you are using Java 9, you can also call readAllBytes() on the InputStream.