0

我有一个程序可以运行并且不会在 Eclipse 中引发运行时错误,结果应该在程序结束时将图像设置为 JButton,但图像永远不会放在按钮上。该程序在 DrJava 中运行良好,但我转移到 eclipse 以制作 jar 文件。

我在另一个发布的问题中看到有人有类似的问题,说图像应该放入项目目录而不是 src 目录,但它没有解释如何实际解决问题......我是 eclipse 新手,所以如果有人可以帮助我谢谢。

这是在我的代码中设置图像的方式:

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"));
      }
    }
  }
4

1 回答 1

0

您将文件名作为参数传递。我猜这个文件名是一个相对文件名。因此,该文件相对于 IDE 启动java命令以执行应用程序的目录:工作目录。

可以从 Eclipse 中的“参数”选项卡下的运行配置更改此目录。但这可能不是你想要的。图标当然应该与您的应用程序捆绑在一起,并使用类加载器加载。将它们放在源文件夹中的一个包下。Eclipse 会将它们与编译的类一起复制到输出目录。如果您为您的应用程序生成一个 jhar,它们将与您的类捆绑在 jar 中。完成此操作后,您只需使用将 URL 作为参数的构造函数,然后传递

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

作为这个 URL 参数。

这将允许您轻松地将图标与应用程序捆绑在一起,并且无论工作目录是什么都将加载图标。

于 2012-07-09T14:25:05.267 回答