Question

I have the following code:

package test;


import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SWTTest {

    public static void main(String[] args) {
        SWTTest test=new SWTTest(new Display());
        test.run();
    }


    private Shell shell;
    private Display display;


    public SWTTest(Display main_display) {
        display=main_display;

        shell=new Shell(display, SWT.DIALOG_TRIM);
        shell.setText("Test window");
        shell.setBackgroundImage(new Image(display,"./image/blue_screen.jpg"));
    }

    public void run() {

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) 
                display.sleep();
        }
    }
}

This is compiling and running. the problem is when I export it as a jar file.
Just to make sure I did it correctly:
Right-click on the project->export...->Runnable Jar file->choosing the right launch configuration, and then 'Finish'.
It creates a jar file, but then when I run it from terminal, I get:

Exception in thread "main" org.eclipse.swt.SWTException: i/o error (java.io.FileNotFoundException: ./image/blue_screen.jpg (No such file or directory))
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.SWT.error(Unknown Source)
    at org.eclipse.swt.graphics.ImageLoader.load(Unknown Source)
    at org.eclipse.swt.graphics.ImageDataLoader.load(Unknown Source)
    at org.eclipse.swt.graphics.ImageData.<init>(Unknown Source)
    at org.eclipse.swt.graphics.Image.<init>(Unknown Source)
    at test.SWTTest.<init>(SWTTest.java:31)
    at test.SWTTest.main(SWTTest.java:13)
Caused by: java.io.FileNotFoundException: ./image/blue_screen.jpg (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at org.eclipse.swt.internal.Compatibility.newFileInputStream(Unknown Source)
    ... 6 more

Why is it running on Eclipse, but not as a jar file?
Why is it all of a sudden can't find the image?

(I will also mention that I added new Source Folder to my project and named it "image", which now sits next to the "src" folder - what I'm trying to say is that "image" folder is a Source folder in my Eclipse project).
So what am I missing here?

Was it helpful?

Solution

When your images are stored in the jar, you need to load them as a resource. Along these lines, but you should close the stream.

BufferedImage image = ImageIO.read(MyClass.class.getResourceAsStream("something.png"));

When you run in Eclipse, you have the images local in your directory, so you can see them with the usual File objects, but not when they are in the jar itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top