0

I have a problem i have never had before and couldnt find a solution on the web. I have a small Programm which uses some images to print a menu.

This is the Class i use to print the Images:

public class ViewImage extends JPanel {
    private static final long serialVersionUID = 1L;
    protected Image image = null;

    public ViewImage(int x, int y, String path) {
        this(x, y, new ImageIcon(path).getImage());
    }

    public ViewImage(int x, int y, Image image) {
        this.image = image;
        this.setBounds(x, y, image.getWidth(null), image.getHeight(null));
    }

    public void paintComponent(Graphics g) {
        int x = ((this.getWidth() - image.getWidth(null)) / 2);
        int y = ((this.getHeight() - image.getHeight(null)) / 2);

        g.drawImage(image, x, y, null);
    }

    public void setImage(String path) {
        this.image = new ImageIcon(path).getImage();
    }
 }

My Images are all part of the classpath an i call them with:

this.getClass().getClassLoader().getResource("MyImage.png").getPath()

Works fine until i package my programm into a jar file and run it from console with:

java -jar MyJar.jar

My programm starts well but no image are printed. No Exceptions, no Errors, nothing.

What can cause such an behaviour?

Mulgard
  • 9,877
  • 34
  • 129
  • 232
  • It could be the location of MyImage.png in the jar-file. Could you unzip the jar-file, and provide a listing of its directory structure? – Henrik Aasted Sørensen Aug 15 '13 at 09:53
  • My Images are all in the root directory when i unpack my jar next to the source-folder and the META-INF – Mulgard Aug 15 '13 at 09:58
  • Cannot you use `getResourceAsStream` instead of trying to get to an actual file? – Thilo Aug 15 '13 at 09:59
  • @MarcTigges : Please have a look at this [answer](http://stackoverflow.com/a/9866659/1057230). Hopefully it might be able to help you too :-) The way you using 'ImageIcon`, it is bound to silently do away with any alarms, that the code might encounter :-) Last link in that post will definitely help you, if you doing it without an IDE :-) – nIcE cOw Aug 15 '13 at 10:01

2 Answers2

4

Before all be sure your resource is correctly loaded (for example with a System.out())!

Instead to use ImageIcon(String location) use ImageIcon(URL location) constructor because your image is not on hdd, but live compressed as URL in your classpath (something like MyJar.jar!/path/to/image.png"); you have to modify your image loading as

this.getClass().getClassLoader().getResource("MyImage.png");
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69
1

The ".getPath()" part of your code excludes the leading part of the URL.
This needs to be present if your resource is part of a jar file.

I suggest you remove the ".getPath()" and use the full URL.
Printing out the full URL is a good idea too, in a System.out.println for example.

davidfrancis
  • 3,734
  • 2
  • 24
  • 21