简体   繁体   中英

how do you add images to the project directory in eclipse?

I have a program that runs and doesnt throw a runtime error in eclipse which should set up an image to a JButton at the end of the program as the result but the image is never put on to the button. The program worked fine in DrJava but I transferred to eclipse in order to make a jar file.

I saw in another question posted that someone had a similar problem that said the images should be put into the project directory not the src directory but it didnt explain how to actually fix the problem... im new to eclipse so if someone could help me out id appreciate it thanks.

here is how the images are set up in my code:

public void tempSelection70 (int fRate, int wbTemp, int rcTons, int a, int r)
  {
    for (int model = 0; model < 7; model++)
    {
      MyArray y = new MyArray(tons70FCharts[model], "t");
      int[][] x = y.getArray();
      int t = x[a][r];
      if (rcTons == t)
      {
        tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
        break;
      }
      else 
      {
        tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
      }
    }
    for (int model = 0; model < 7; model++)
    {
      MyArray y = new MyArray(flow70FCharts[model], "f");
      int[][] x = y.getArray();
      int t = x[a][r];
      if (fRate == t)
      {
        tableButton = new JButton(new ImageIcon(tablesFor70[model], tablesFor70[model]));
        break;
      }
      else 
      {
        tableButton = new JButton(new ImageIcon("CANNOT_FIND_MODEL.GIF", "SCROLL"));
      }
    }
  }

You're passing a file name as argument. I guess this file name is a relative file name. So the file is relative to the directory from which your IDE launches the java command to execute your application: the working directory.

This directory can be changed from the run configuration in Eclipse, under the tab "Arguments". But this is probably not what you want. The icons should certainly be bundled with your application, and loaded with the class loader. Put them under a package in your source folder. Eclipse will copy them to the output directory, along with the compiled classes. And if you generate a jhar for your app, they will be bundled in the jar with your classes. Once this is done, you just have to use the constructor taking a URL as argument, and pass

SomeClassOfYourApp.getResource("/the/package/of/the/image.png")

as this URL argument.

This will allow you to bundle the icons with the app easily, and will load the icons whatever the working directory is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM