Eclipse's workspace: Shall I put my images in 'src' or 'bin' folder?

前端 未结 7 1730
梦谈多话
梦谈多话 2020-12-17 01:39

I\'m working in a project in Java and sometimes all my images randomly dissapeared from the project\'s bin folder. It is getting very annoying because I have to put everythi

相关标签:
7条回答
  • 2020-12-17 02:32

    Follow these two steps. Worked well for me in Eclipse Kepler.

    1. Bring your image or other resource files into your Java project

      i. Mouse right click on your Java project and do: New -> Source Folder. In this example, I call my folder "res".

      ii. Go to your file browser and you should see this "res" folder under your Java project's root folder. Now copy or move your image and other resource files into it.

      iii. Now go to Eclipse and right click on this "res" folder and do: Refresh. You should see these files show up in it.

      iv. Now build the project and you should see your resource files get copied into the build target "bin" folder.

    2. Now in your class (e.g. your own JFrame class as indicated by the this in my sample code below) you can access the resource file and note the leading "/" to indicate file location relative to binary root:

      Image img = new ImageIcon(this.getClass().getResource("/MyImage.gif")).getImage();
      

    Another note: you can use multiple such resource folders to organize your resources. After project build, they all go into the build target root "bin" folder. And of course, you can export your project as "Runnable Jar File", then you can run your application standalone since all resources are automatically packaged into your jar file.

    0 讨论(0)
提交回复
热议问题