I took this code straight out of 'Java all in one for Dummies' …why doesn't it work?

浪尽此生 提交于 2019-11-30 23:17:34

the image is in the same folder as my project package folder

That's it.

As written, your program looks for the image in the current working directory, not the package hierarchy.

From the Javadoc for the constructor taking String, it reads the image from the specified filename, as desired. However, when you specify a relative path, that means to read relative to the working directory that the application is running in.

To work around this, you have 2 options:

  • Specify the image filename relative to the working directory your IDE runs your program in. I believe Eclipse runs applications in the project root directory, and the source package hierarchy is rooted at src. In this case it'll work if you specify src/TestImage.jpg. The disadvantage is that if you ever run your program from a different directory, you'll have to move the image file along with it. This is inconvenient for distribution/packaging, because you can't just drop the JAR file and have it run.

  • Use Java's resource loader to load the image file from the package hierarchy. To do this, first use

    getClass().getResource("TestImage.jpg")
    

    to get a URL for the image (relative to the package root). See that ImageIcon has a constructor that accepts a URL to read the image from. So you should read the image using

    new ImageIcon(getClass().getResource("TestImage.jpg"))
    

    The advantage of being relative to he package hierarchy is that the program can be run from any location, and the image can be bundled with your app in a single JAR file.

    Aside: it's best practice to create a package in which you place both code and resources (rather than just placing them in the package root). In that case, pass "com/example/someapp/TestImage.jpg" instead.

Try:

ImageIcon image = new ImageIcon(getClass().getResource("TestImage.jpg"));

See How to Use Icons tutorial for more details, in particular Loading Images Using getResource section.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!